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

Objective C parameter passing

ref:
http://stackoverflow.com/questions/2892520/passing-arguments-by-value-or-by-reference-in-objective-c

Jared P is wrong, objective-C only support passing parameters by value. The problem here has probably been fixed already (Since this question is more than a year old) but I need to clarify some things regarding arguments and Objective-C.

Objective-C is a strict superset of C which means that everything C does, Obj-C does it too.

By having a quick look at Wikipedia, you can see that Function parameters are always passed by value

Objective-C is no different. What’s happening here is that whenever we are passing an object to a function (In this case a UILabel *), we pass the value contained at the pointer’s address.

Whatever you do, it will always be the value of what you are passing. If you want to pass the value of the reference you would have to pass it a **object (Like often seen when passing NSError).

This is the same thing with scalars, they are passed by value, hence you can modify the value of the variable you received in your method and that won’t change the value of the original variable that you passed to the function.

Here’s an example to ease the understanding:

If you wanted to be able to modify i, you would have to pass the value of the reference by doing the following:

ref:
http://stackoverflow.com/questions/22213197/is-objective-c-pass-by-value-or-pass-by-reference

C does not support pass-by-reference and Objective-C, being a strict superset of C doesn’t either.

In C (and Objective-C) you can simulate pass-by-reference by passing a pointer, but it’s important to remember that you’re still technically passing a value, which happens to be a the value of a pointer.

So, in Objective-C (and C, for the matter) there is no concept of reference as intended in other languages (such as C++ or Java).

This can be confusing, so let me try to be clearer (I’ll use plain C, but – again – it doesn’t change in Objective-C)

Objective properties

ref:

  1. http://stackoverflow.com/questions/8927727/objective-c-arc-strong-vs-retain-and-weak-vs-assign?rq=1
  2. http://stackoverflow.com/questions/11013587/differences-between-strong-and-weak-in-objective-c
  • atomic (default)
  • nonatomic
  • strong=retain (default)
  • weak
  • retain
  • assign (default)
  • unsafe_unretained
  • copy
  • readonly
  • readwrite (default)
  • strong (iOS4 = retain )

    it says “keep this in the heap until I don’t point to it anymore”
    in other words ” I’am the owner, you cannot dealloc this before aim fine with that same as retain”
    You use strong only if you need to retain the object.

    By default all instance variables and local variables are strong pointers.

    We generally use strong for UIViewControllers (UI item’s parents)
    strong is used with ARC and it basically helps you , by not having to worry about the retain count of an object. ARC automatically releases it for you when you are done with it.Using the keyword strong means that you own the object.

    weak

    it says “keep this as long as someone else points to it strongly”
    the same thing as assign, no retain or release
    A “weak” reference is a reference that you do not retain.
    We generally use weak for IBOutlets (UIViewController’s Childs).This works because the child object only needs to exist as long as the parent object does.
    a weak reference is a reference that does not protect the referenced object from collection by a garbage collector.
    Weak is essentially assign, a unretained property. Except the when the object is deallocated the weak pointer is automatically set to nil
    Example :

    Strong & Weak Explanation

    by BJ Homer

    Imagine our object is a dog, and that the dog wants to run away (be deallocated).

    Strong pointers are like a leash on the dog. As long as you have the leash attached to the dog, the dog will not run away. If five people attach their leash to one dog, (five strong pointers to one object), then the dog will not run away until all five leashes are detached.

    Weak pointers, on the other hand, are like little kids pointing at the dog and saying “Look! A dog!” As long as the dog is still on the leash, the little kids can still see the dog, and they’ll still point to it. As soon as all the leashes are detached, though, the dog runs away no matter how many little kids are pointing to it.

    As soon as the last strong pointer (leash) no longer points to an object, the object will be deallocated, and all weak pointers will be zeroed out.

    When we use weak?

    The only time you would want to use weak, is if you wanted to avoid retain cycles (e.g. the parent retains the child and the child retains the parent so neither is ever released).

    retain = strong

    it is retained, old value is released and it is assigned retain specifies the new value should be sent retain on assignment and the old value sent -release
    retain is the same as strong.

    apple says if you write retain it will auto converted/work like strong only.

    assign

    assign is the default and simply performs a variable assignment
    assign is a property attribute that tells the compiler how to synthesize the property’s setter implementation
    I would use assign for C primitive properties and weak for weak references to Objective-C objects.

    Strong vs Weak reference

    A strong reference (which you will use in most cases) means that you want to “own” the object you are referencing with this property/variable. The compiler will take care that any object that you assign to this property will not be destroyed as long as you (or any other object) points to it with a strong reference. Only once you set the property to nil will the object get destroyed (unless one or more other objects also hold a strong reference to it).

    In contrast, with a weak reference you signify that you don’t want to have control over the object’s lifetime.

    The object you are referencing weakly only lives on because at least one other object holds a strong reference to it. Once that is no longer the case, the object gets destroyed and your weak property will automatically get set to nil.

    The most frequent use cases of weak references in iOS are:

    • delegate properties, which are often referenced weakly to avoid retain cycles
    • subviews/controls of a view controller’s main view because those views are already strongly held by the main view

    Atomic vs Nonatomic

    atomic vs. nonatomic refers to the thread safety of the getter and setter methods that the compiler synthesizes for the property. atomic (the default) tells the compiler to make the accessor methods thread-safe (by adding a lock before an ivar is accessed):

    and nonatomic does the opposite. The advantage of nonatomic is slightly higher performance.
    On iOS, Apple uses nonatomic for almost all their properties so the general advice is for you to do the same.

Navigating to a new UIViewController from a UIViewController

First we put a button there and correspond it to a method called nextPage.

Then in that method, you use pushViewController to animate a new controller coming in.

…where MTBookCoverViewController is just a standard, empty UIViewController.

UIViewControllers talk to each other through delegates

The controller manages the communication between the view and the model. It takes the data from the model and communicates it to the view for display.

In the same vein, the controller also takes the changed data (due to user interaction or something else) and communicates it back to the model.

Say SmoothiesViewController and EditRecipeViewController need to communicate with each other.

Declare Protocol and use delegate variable

First declare protocol like this:

EditRecipeViewController.h

Once your protocol is set. You declare a delegate:

Whoever conforms to that delegate MUST implement the methods in that protocol. Because this class with the delegate, will be calling these methods, and the classes that conform to this protocol, must execute these methods.

In EditRecipeViewController.m it is used like this:

First, we check to see if our delegate responds to such method. If it does, then call it. This means that ALLLLL the UIViewControllers that conforms to our EditRecipeDelegate protocol must execute their method of editRecipeDidCancel.

UIViewController conforms to protocol

Say SmoothiesViewController conforms to our EditRecipeDelegate

This means in our SmoothiesViewController.m file, we must implement the required protocol methods:

Data Model (mvc)

You have your business logic in Recipes:

Recipe.h:

Recipe.m

We put our business logic into a data structure. Implement some methods that manipulate this business logic. This is called our data model.

DataModel.h:

DataModel.m – this is where we manipulate our business logic into a data structure and implement wrapper methods such as add, delete, search, indexOf…etc.

Firing events through Notifications

Model — fire events –> Controller

Our Data Model communicates with other UIViewController by firing Notifications like this in our DataModel.m:

Thus, from our DataModel, we fire a notification called FavoritesChangedNotification or RecipesChangedNotification, which are NSStrings defined in our DataModel.h like this:

Whoever is listening for these notifications will execute their @selector method code.

UIViewControllers listening for Notifications

In our UIViewController we set it up like this:

You can see we have a strong reference to the shared Data Model.

In short: the owner of an object will retain that object and is ultimately responsible for releasing it when it no longer uses that object. When an object is retained, this is called a strong reference. SmoothieViewController has a strong reference to DataModel, because it created that object. SmoothieViewController owns the DataModel for as long as it is alive (which is until this app exits) and will release it in its dealloc.

Whenever we have other UIViewControllers that updates our Data Model like RecipeDetailsViewController, we make it a so-called weak reference like this:

note:
RecipeDetailsViewController does not own the object and therefore does not retain it. Because RecipeDetailsViewController is guaranteed that the DataModel instance will be around for at least as long as it is (i.e. until the user exits the app), it has no need to retain it.

In general, if you pass along pointers to objects you should make them weak references (using the “assign” property semantics), to signify that the object you are giving it to does not assume ownership. You only use “retain” or “copy” when you are not guaranteed that the object may stick around, in which case you become responsible for releasing it when the time comes.
end note.

We then have a UITableViewController displaying the data in our dataModel variable.
What happens if our dataModel changes data? Then in our DataModel.m, these methods will fire Notification like this:

So Data Models post or fire these notifications. We have our UIViewController’s listen for them.

Our UIViewControllers listen up for notifications through [NSNotificationCenter defaultCenter]’s addObserver:

First, make sure the notification strings are set from whichever data models are firing them. In our case its in DataModel.h:

then in your UIViewController’s m file, we set up NSNotificationCenter’s addObservewr:

Once we set up the observer, we implement the method that will execute whenever we receive such a notification in our UIViewController:

What this means is that our UIViewController basically are listening for notifications from our data models. Once there is a notification, we update our view (in our case UITableViewControlelr) accordingly.

Also, remember to remove those observers in your dealloc:

Controller updates Model

Controller — updates –> Model

Now in your ViewControllers we also update our DataModel through using the self.dataModel removeRecipeAtIndex method. Our users manipulate our UITableView, and the interaction calls our commitEditingStyle:forRowAtIndexPath, which then manipulates our weak reference dataModel variable. That is how Controllers update our Models.

Working with directories and files in Sandbox

Home Directory

Naturally, you’d have the documents folder in your home directory as well:

which will give you something like this:

homeDir is: /var/mobile/Applications/DF2ACE23-C3D0-444B-9D25-7E56F102595A/Documents

This is where you save your files in your sandbox.

Writing text to a txt file

First, you have to get the name of your path + file. Something like this:

/var/mobile/Applications/DF2ACE23-C3D0-444B-9D25-7E56F102595A/Documents/test.txt

We do this by appending our file name to the home directory. In our case, let’s say self.filename is test.txt:

Then you use that path string and use method writeToFile: to write contents to that file:

full method:

Reading text from file in sandbox

Writing image to your sandbox

We first create an image. Make sure the image resource exists.
Then we give it a string name and then make sure homeDir is same as we’ve displayed above. Plug in and use like so:

where myFile.homeDir is: /var/mobile/Applications/DF2ACE23-C3D0-444B-9D25-7E56F102595A/Documents

Reading images from your sandbox

Used like this:

Implementation:

count recursively

Abstract class and virtual functions

char array copying and pointer manipulation

Basically, the idea is that you DO NOT touch the original arrays. Instead, you declare two char pointers and point to them. Then, assign the data from source to destination as you move each pointer down the arrays.

result:

destination is: ||
source is: |BLUR SAMPLE|
destination is: |B|
destination is: |BL|
destination is: |BLU|
destination is: |BLUR|
destination is: |BLUR |
destination is: |BLUR S|
destination is: |BLUR SA|
destination is: |BLUR SAM|
destination is: |BLUR SAMP|
destination is: |BLUR SAMPL|
destination is: |BLUR SAMPLE|
copy done. final destination is: |BLUR SAMPLE|