Category Archives: C/C++/Objective-C

debugging with xCode (pt 4) – Warning and Errors

Usually, adding a lot of ‘todo’ comments is not a good idea because it will rarely be seen by others.

Hence we use #warning to throw a warning for our message when the developer compiles.

If you want it to be an error:

Playing a sound using Breakpoint

You can also put sounds in your code by first adding a break point to where you want the sound to happen. Then:

Edit Breakpoint >> Action >> Sound >> choose a sound file.

Playing a sound is a good way to know if a certain code path has been reached without having to look through the logs. You can also provide your own custom sounds in case you want to play an explosion for a particular bad crash.

To do so, just drop your sound files in this folder:

YOUR_HOME_DIRECTORY/Library/Sounds

debugging with xCode (pt 3) – Logging with break points

Logging with Breakpoints

Say at a certain line in your code, you want to log some statements. You do so by first adding a breakpoint by clicking on the vertical strip of space on the left side of your source file. Then you right click on your breakpoint and select ‘edit break point’.

debugger3_edit_brpt

For option Action, select Log Message and type in some message you would like to appear. For example, the name of the file would be a good choice. Also, the name of the method you’re in is also another great choice. You do so by using %B.

debugger3_log_msg_console

You can also log custom variables by putting variables in between %%

debugger3_logging_variables

Now, execution will stop at your breakpoint and print out your log messages

debugger3_stops_at_brpt

However, say you want the execution to keep going. You’d check the “Automatically continue…” checkbox so that you get the logging and all that, but execution continues.

debugger3_brpt_continue

Now it just uses your breakpoint to do whatever Action you intended and continues on to the next one.

debugger3_continues

Voice Logging

Next to Action, there is a + and button. Use the + button to add more actions. Select Log Message and there is a Speak Message option. Select it and it will voice your logs.

Debugger Command

Add a breakpoint on a line right beneath a variable say:

Control click or right click the breakpoint, click ‘Edit Breakpoint’, then select select “Debugger Command” from the dropdown. In the text field type the follow:

po is a debugger command that will print out the contents of an object. You can keep adding Actions >> Debugger Command and po-ing variables.

Logging with Date

Action >> Debugging command

The expr command will evaluate an expression in real time. The expression command needs to know the actual type of the returning value, so a cast is necessary. Since there is no return type for NSLog, the return type is cast to a void value. Build and run.

You should now see the following:

2012-12-20 08:57:39.942 GiftLister[1984:11603] dataStore:

Being able to add NSLog messages via. breakpoints means you no longer have to stop the program just to log important data, there’s no chance of introducing new bugs because you are not touching the code, but best of all, there’s no last minute scrambles to remove all your debug statements the night before release.

Disabling breakpoints before a release

Say you’re ready to turn in a release and you want to disable all the breakpoint logging. Simply go to your navigator and press the debug section. Then select ‘Disable breakpoints’ and that’s it. Now your code will run without all the breakpoint logging.

debugging3_disable_brpts

debugging with xCode (pt 2) – stopping at exceptions

Stopping at Exceptions

By default, when you run into an error, you’ll get a SIGART error that really does not tell us anything.

debugging2_SIGART

Currently, you cannot see the source of the compile error. To find it, you need to add an exception breakpoint to track down the source of the error.

So switch to the breakpoint navigator as shown below

debugging2_on_exception_throw

The Exception field gives you the option of activating the breakpoint in Objective-C, C++, or All. Keep the default option of All.

The Break field in the dropdown allows you to pause execution on whether an error is thrown or caught. Keep it selected on thrown. If you are actually making use of exception handling in your code, then select ‘On Catch’. For the purposes of this tutorial, leave it ‘On Throw’.

debugging2_exception_brpt

Now you’ll be able to see where the error occured.

debugging2_error_src

debugging with xCode (pt 1) – showing variables

Showing Variables

Your debugging console can be toggled by the middle button on the top right hand corner. Mainly, it shows your variables, and log outputs.

debugging_toggle_console

When you run and debug a project by throwing in breakpoints, you’ll see that your debugging console only has log outputs like so. There are no variables…you only see your output console.

debugging_no_variables

In order to have the variables showing, go to:

xCode >> Preferences

debugging_xcode_pref

and you should see and select Behaviors. Then you will see panels for Build, Testing, Running….

Under Running, select Start and on the right hand side select Variables and Console for debugger showings.

debugging_behaviors_start

Do the same for ‘Pauses’ and ‘Generate Output’.

debugging_behaviors_pause

debugging_behaviors_output

The ‘Variables & Console’ option tells the debugger to show the list of local variables as well as the console output each time a debugger session starts. If you wanted to view just the console output, you would select ‘Console View’. Likewise, if you wanted to see just the variables, you would select the ‘Variable View’.

The ‘Current Views’ option defaults to the last debugger view on your last debugger session. For example, if you closed Variables and opted to just the view the console, then just the console would open next time the debugger was started.

Now, you will see the variables appear when you debug

debugging_variables

Function vs Method

A function is a piece of code that is called by name. In this case, name of the function. It can be passed data to operate on (ie. the parameters) and can optionally return data (the return value).

All data that is passed to a function is explicitly passed, because there is no ‘self’ or ‘this’, or any identification of an instantiation of a class (object) to operate from.

In this case, if we are to pass any data into myFunction, we can only do so through parameter variable int i. There is no other way around it.

A method is a piece of code that is called by name that is associated with an object. This object is instantiated of a class.

In most respects, a method is identical to a function except for two key differences.

1) It is implicitly passed for the object for which it was called.
2) It is able to operate on data that is contained within the class (remembering that an object is an instance of a class – the class is the definition, the object is an instance of that data).

In the example below, length method is used to get the length of a string. But what string? The string of the object instantiation data1. The ‘implied’ use of this object member variable myName is called implicit parameter.

definition:

Thread Safety in ios

ref – http://quellish.tumblr.com/post/101831085987/implementing-thread-safety-in-cocoa-ios

You have just introduced “threads” to your application, because doing everything on the same thread as the UI was starting to noticeably bog things down. At some point you have run into strange crashes or exceptions. Your application no longer behaves as it used to.

One problem you have likely introduced is sharing data between threads. If two threads can be changing something, you’re asking for trouble. The common solution to this problem is to protect access to that resource: to introduce some form of locking on the resource to only allow one thing to touch it at a time.

In Objective-C there are a number of ways to deal with this, with the most common being use of the @synchronized keyword to protect access to a block of code.
The @synchronized keyword

In Objective-C the @synchronized keyword provides an implicit reentrant lock on a unique identifier for a block of code. For example:

This prevents the code inside that statement from executing until any contention on foo is released. This prevents more than one thread from using that lock at a time.

Because the lock is implicit, there is overhead even when the lock is not in contention. If nothing else is accessing the lock, the system still has to find the lock, which takes time. The lock used is recursive, which is more expensive than a non-recursive lock. Additionally, the @syncrhonized keyword does put into place an exception handler that adds some additional overhead. Because @synchronized uses a lock, it’s possible to use it in ways that result in a deadlock.

@synchronized is a blunt instrument, and unfortunately is often used to hammer away “threading problems”.

Lock-free synchronization

The point of synchronizing access to something is to ensure only one thing can access it at a time. On MacOS and iOS we have the concept of queues for concurrency. A serial queue is an ideal way to protect access without the potential costs of locking. If every access to the protected resource occurs through a serial queue the problem is solved – the queue guarantees that only one thing will be accessing it at a time. For example:

Because the serial queue executes work in FIFO order and only one block at a time, the statement is protected. Unlike using a lock, this can’t deadlock.

This is the preferred method for protecting a resource shared between threads on MacOS and iOS.
Not needing synchronization at all

The recommended solution for this problem is not to have it all. If you are sharing a mutable resource between threads, question why.

You may have noticed that much of Foundation is class clusters that provide both immutable (i.e. NSString) and immutable (i.e. NSMutableString) versions of a given class cluster object. An immutable object cannot be changed after it is created – it has a finite, determinate state and life cycle. Because of this, immutable objects are safe to exchange betweeen threads – there is no problem with two threads changing the object at the same time. Mutable objects should be considered unsafe unless they are specifically documented to be safe to access across threads.

Unfortunately few objective-c developers follow this practice even though it is one of the SOLID object oriented design principles. The developer will run into a mysterious crash or exception, google it, and after reading a few Stack Overflow articles start stamping @synchronized all over the place.
In practice

Implementing a reader-writer lock or the equivalent in objective-c is easy, and easy to get wrong. You will commonly see something like this:

Which isn’t effective for several reasons. Each method is synchronizing on self, so ANY access to self or it’s members will cause a contention.

By overriding the accessor methods for the foo property and accessing the instance variables directly the application may not be correctly managing the memory associated with foo.

A better implementation would be:

This uses a private property to ensure correct memory management. Note that because it’s of type id, we retain it strongly. If foo were a type that is a class cluster, we would prefer declaring it as copy rather than strong. That would ensure that even if it were set with a mutable object, the accessor would make an immutable copy before setting it. Instead of using @synchronized to provide an implicit lock, we’re using a serial queue to protect access to the private property. Note that in the case where we return the value in the getter we use dispatch_sync to make the calling thread wait for the result. This does use a lock, but the lock does not have most of the disadvantages of @synchronized and is only used in the reading case. An alternative would be to pass a block to be executed when the value is available:

This not only removes the need to block, but executes asynchronously.

Thread Basics (Instantiations)

SomeClass header

SomeClass implementation

main

log output:

Thread B processing on object 0x7fe839416a70 ‘s method, member variable address: 0x7fe839416a78, number just changed to 0
Thread B processing on object 0x7fe839416a70 ‘s method, member variable address: 0x7fe839416a78, number just changed to 1
Thread A processing on object 0x7fe83960e340 ‘s method, member variable address: 0x7fe83960e348, number just changed to 0
Thread A processing on object 0x7fe83960e340 ‘s method, member variable address: 0x7fe83960e348, number just changed to 1
Thread B processing on object 0x7fe839416a70 ‘s method, member variable address: 0x7fe839416a78, number just changed to 2
Thread B processing on object 0x7fe839416a70 ‘s method, member variable address: 0x7fe839416a78, number just changed to 3
Thread A processing on object 0x7fe83960e340 ‘s method, member variable address: 0x7fe83960e348, number just changed to 2

As you can see

Thread A processes on object 0x7fe83960e340
Thread B processes on object 0x7fe839416a70

The access different member variables, in particular

Thread A processes on object 0x7fe83960e340’s member variable 0x7fe83960e348
Thread B processes on object 0x7fe839416a70’s member variable 0x7fe839416a78

Both threads do their work on their own respective objects because those objects were allocated on the thread’s own stack in main’s

Threads Basics (static, class methods, and singletons)

Class methods are shared by threads

All methods who run a class method on a class name are using the same class and running through that one method. That class method acts as an entry point. You do this by looking at the address of self.

If you run couple of threads through this classMethod, you should something like this:

classMethod – thread B, self address is: 0x107159380
classMethod – thread A, self address is: 0x107159380
classMethod – thread C, self address is: 0x107159380

They all have the same address for ‘self’. Which means there exist only one blueprint of the class in which these class methods belong to.

static variables are shared by threads

you’ll see that in the output, they all display the static variable’s address, which is the same for all threads:

classMethod – thread B, local static int number’s address is: 0x1071594e8
classMethod – thread C, local static int number’s address is: 0x1071594e8
classMethod – thread A, local static int number’s address is: 0x1071594e8

local variables are not shared. They belong to their own thread stack

you’ll see from output the the addresses of the local variable is different, which tells us that each thread have their own local variables:

classMethod – thread D, local int number’s address is: 0x11420fc44
classMethod – thread B, local int number’s address is: 0x114109c44
classMethod – thread C, local int number’s address is: 0x11418cc44
classMethod – thread F, local int number’s address is: 0x114315c44
classMethod – thread E, local int number’s address is: 0x114292c44

non-static variables are not allowed

If we were to declare an int number in our class:

and you try to use it in your static method, you’d get an error. Because only static variables are used in static methods. Its not intuitive or possible for a class method to keep track of instantiated variables. It simply does not work this way.

the variable ‘number’ is connected to an instantiation (object) of SomeClass.

No static class variables

You cannot declare ‘number’ in our previous example to be static because in objective c, there are no class static variables.

However, you CAN declare a static variable globally and use it in SomeClass’s static method. That is the basis of how a lot of singletons are made.

Example Singleton

.h

.m

As you notice we don’t let others copy or allocate our singleton by returning self. ….because there can be only 1 singleton.

Full Example

SomeClass header

SomeClass implementation

main – appdelegate

Result

classMethod2 – thread D, self address is: 0x107159380
classMethod – thread B, self address is: 0x107159380
classMethod – thread A, self address is: 0x107159380
classMethod – thread C, self address is: 0x107159380
classMethod2 – thread E, self address is: 0x107159380
classMethod2 – thread F, self address is: 0x107159380
classMethod2 – thread D, local static int number’s address is: 0x1071594ec
classMethod – thread B, local static int number’s address is: 0x1071594e8
classMethod – thread C, local static int number’s address is: 0x1071594e8
classMethod – thread A, local static int number’s address is: 0x1071594e8
classMethod2 – thread F, local static int number’s address is: 0x1071594ec
classMethod2 – thread E, local static int number’s address is: 0x1071594ec
classMethod – thread A, local int number’s address is: 0x114086c44
classMethod2 – thread D, local int number’s address is: 0x11420fc44
classMethod – thread B, local int number’s address is: 0x114109c44
classMethod – thread C, local int number’s address is: 0x11418cc44
classMethod2 – thread F, local int number’s address is: 0x114315c44
classMethod2 – thread E, local int number’s address is: 0x114292c44

Factory Methods in Objective C and iOS

ref – http://stackoverflow.com/questions/19450940/what-is-the-purpose-of-using-a-factory-method-in-objective-c-context

Objective-C does not have constructor methods that are available in other programming languages. Factory methods are essentially Objective C’s constructor methods. They allow you to allocate memory for your object and initialize the values.

In your class, add methods with this pattern:

Then in main, you can do:

It saves you from having to do this:

Furthermore

A factory method can be any class or instance method which returns a newly created and initialized object.

A “class factory method” in a more strict Objective-C context is any class method of a class Class whose name begins with class.., with its prefix stripped and first letter lowercased. Example for class Foo:

One reason to use class factory methods is for convenience. If you have a class Foo it may be created as follows in the usual way:

A convenient class factory method may now be used as this:

However, there are other reasons where a class factory method is useful:

Suppose for example that the initWithParam: method can fail. Then there is much confusion about how this should be handled: should one throw an exception within init? Or should one return nil? There is controversy debate about the right approach in the community. Both approaches have subtle issues, including memory leaks which can not be avoided.

Thus, the most reasonable approach in such a case would be to use a class factory method with an error parameter. Here, you would get a Foo object as follows:

Now, the rule is: If foo is nil, there was an error, and one can obtain detailed info about the error with the output parameter error:

Typically, the implementation would look as below:

Another reason is to implement “class clusters”. That basically means that a class factory method returns a subclass of the class. An example is the NSStream class.

The NSInputStream class has a class factory method:

This returns a specialized class of NSInputStream.

In the pre-era of ARC there is an important detail:

Objects returned from a class factory method are ‘autoreleased’. In other words, the client receiving the object does not own it – and thus does not need to release it.

Nowadays, with ARC these details became blurred: you do not need to release those objects manually anyway. How and when the object gets actually released is also subject to compiler optimizations.

static in objective c vs java

ref –
http://stackoverflow.com/questions/4965048/static-variables-in-objective-c-what-do-they-do
http://stackoverflow.com/questions/2649213/in-laymans-terms-what-does-static-mean-in-java

OBJECTIVE C STATIC VARIABLES

In both C and Objective-C, a static variable is a variable that is allocated for the entire lifetime of a program.

This is in contrast to automatic variables

  • whose lifetime exists during a single function call
  • and dynamically-allocated variables like objects, which can be released from memory when no longer used
  • More simply put, a static variable’s value is maintained throughout all function/method calls.

    On the other hand

    Say you have this:

    Every call to f() will return the value 15.

    static variable to mimic class variables

    In the context of Objective-C classes, static variables are often used to mimic class variables, as Objective-C does not have class variables (other languages, such as Java, do). For instance, say you want to lazily initialize an object, and only return that object. You might see this:

    obj will be initialized the first time classObject is called; subsequent invocations of classObject will return the same object. You could check this by logging the address of the object:

    NSLog(@”obj is at %p”, [MyObject sharedObject]);
    NSLog(@”obj is at %p”, [MyObject sharedObject]); // Will print the same address both times

    Furthermore, obj will be visible to all methods in MyObject.

    This technique is used to implemented singleton classes in Objective-C as well.

    Static Variables in Java

    static means that the variable or method marked as such is available at the class level. In other words, you don’t need to create an instance of the class to access it.

    So, instead of creating an instance of Foo and then calling doStuff like this:

    You just call the method directly against the class, like so:

    There’s just one of it because it belongs to the class.
    Thus, it should be mentioned that a static field is shared by all instances of the class, thus all see the same value of it.