Category Archives: iOS

basic inheritance

If the public method is NOT over-ridden, your class extends the hierarchy, then call the public method, you’ll use the public method declared FARTHEST from you

Say you have a Base class with a public method called “publicMethod”

Then, you have a Child1 class that derives from Base class. It does not over-ride publicMethod in Base class.

Then, you have a Child2 class that derives from Child1 class.

When you go:

It will call on publicMethod in the Base class.

If the public method IS over-ridden, your class extends the hierarchy, then call the public method, you’ll use the public method declared CLOSEST to you

Child2 derives from Child1

Then you go:

Then it will call Child1’s anotherPublicMethod

Cascade – every inheritance node needs to run

If you want a certain method tor un from Base to Child1, to Child2, make sure you use [super …] in the beginning of your call. A great example would be the init method.

Base’s init

Child1’s init

Child2’s init

Allocating a Child2 object

would have the result:

— Base.m – creating Base object —
— Child1.m, init Child1 object —
— Child2.m – init Child2 object

Child2’s init calls [super init], which is Child1’s init
Child1’s init calls [super init], which is Base’s init
Base’s init calls [super init], which is NSObject’s init

When NSObject’s init returns, our execution moves forward and displays Base init method’s log
When Base init method returns, our execution moves forward and displays Child1’s init method’s log
When Child1’s init method returns, execution moves forward and displays Child2’s init method’s log.

Hence, we have

— Base.m – creating Base object —
— Child1.m, init Child1 object —
— Child2.m – init Child2 object

Core Data Part 5 – deleting

Core Data part 3 – Add Data

DEMO PROJECT

Given that,

1) You have your Data Stack set up
2) You have a model set up, and generated your model object which derives from NSManagedObject. Make sure your properties are @dynamic so that it uses the superclass’s synthesis (via NSManagedObject).

Remember, if you do not use @dynamic, and instead use @synthesize, it means you will be writing the getter/setter method yourself and if you do not write it correctly, the data you save using Core Data will not be there when you restart the app.

for xCode 7 and after, category file is generated

If you are using xCode 7 or after, a category file is generated along with the entity file like so:

  • Person+CoreDataProperties.h
  • Person+CoreDataProperties.m
  • Person.h
  • Person.m

The reason for this is because whenever new entity files are generated by doing:

  • click on .xcdatamodeld file
  • then Editor >> Create NSManagedObject subclass

you won’t have your Entity files overwritten. All your properties and methods will still be there. Instead, xCode will over-ride the Category file(s) instead.

Hence put all your code in Person, and leave the Category file alone.

Implementing the Entity files

Person.h

Person.m

Adding data

In your CoreDataStack.h, we’ll make 2 methods.

  1. create a new person
  2. display on all the people who’s in the database into our console.

Here are the few important issues when Adding a Person using core data:

1) use insertNewObjectForEntityForName method for Core Data to return you a managed object so you can initialize it with data.

2) Make sure you save context on it.

Here are the few important issues when fetching using core data:
executeFetchRequest gets what we need according to a request. It returns an array and you can iterative through it and display it.

ViewController button and responder

In your UIViewController, add a button and a responder method for both Adding a Person and Logging all the people to the console

Now let’s add a display button. Give it a responder method name displayAll.

Implement the button responders:

Now, go ahead and run the project using xcode. Press the Add Person button to add Person objects into the database, and see the results through your console.

Then press the display button to show all the Person objects that’s been saved into the database. Restart the app using your xcode project, press the display button again, and look at the log console to see the objects you’ve saved from before.

Custom TableView Cell

Create the TableView

First, we create a tableView member variable in our ViewController

Second, we declare its property, and synthesize

Then in the viewDidLoad, we allocate for the tableView and add it to the view hierarchy.

Result:

emptyTable

We now have an empty table. However, it doesn’t do anything because we need to conform to the UITableViewDataSource to let it know what kind of data it should have and display.

Conforming to UITableViewDataSource

We need to modify the table to our liking by working with its data source delegate methods. We first make it our ViewController conform to the UITableViewDataSource delegate:

Make sure you assign the dataSource

After declaring the protocol, you’ll get warnings to implement the required methods:

Implement the required numberOfRowsInSection method. We say we want 8 rows

Implement the required cellForRowAtIndexPath method. We tell the delegate that we want to draw our cell like standard but with certain text:

Result:

textTable

Creating the Custom Cell

First, create MyCustomTableCell class:

MyCustomTableCell.h

MyCustomTableCell.m

In your UIViewController, let’s change the cellForRowAtIndexPath method so that it takes our custom cell:

Result:

customCell

getting location of core data sqlite file

http://stackoverflow.com/questions/24133022/ios-8-store-sqlite-file-location-core-data

Then, copy it.

Open up finder, and press command + shift + g. A location window will pop up and paste the copied path into it. Press enter, and you’ll see the .sqlite file

When to use delegate, blocks, or notifications

http://stackoverflow.com/questions/21771606/objective-c-delegate-or-c-style-block-callback

Delegates should be used when there are multiple “events” to tell the delegate about and/or when the class needs to get data from the delegate. A good example is with UITableView.

A block is best used when there is only one (or maybe two) event. A completion block (and maybe a failure block) are a good example of this. A good example is with NSURLConnection sendAsynchronousRequest:queue:completionHandler:.

A 3rd option is notifications. This is best used when there are possibly multiple (and unknown) interested parties in the event(s). The other two are only useful when there is one (and known) interested party.

ARC is not a garbage collector!

ref – http://stackoverflow.com/questions/12318398/how-can-we-explicitly-call-garbage-collector-in-arc-also-is-there-a-way-we-can

There is no garbage collection with ARC, so there is nothing to call. If you control the scope and ownership of your objects, ARC will look after the memory use for you.

Apart from assigning ‘nil’ to a reference or letting the reference go out of scope, the only other consideration is whether you have some extra reference to the object (such as putting it into a NSArray) that has it’s own need to retain the object.

Note: An object pointer (or reference) gets pushed onto the stack. When you go out of your scope, that references gets popped, thus essentially nil-ing it.

Or in other words, pointing the reference away from the object on the heap, and thus making a -1 on that object. When that object has NO strong references to it anymore, it’s dealloc will be called.

Retain cycle with Blocks in iOS

references
https://zearfoss.wordpress.com/2012/05/11/a-quick-gotcha-about-blocks/
http://stackoverflow.com/questions/14649661/defining-objective-c-blocks-as-properties-best-practice/14650386#14650386

First, please read Block Basics

But why do we use copy to keep the Block around?

By default blocks are created on the stack. Meaning they only exist in the scope they have been created in. This is an optimization, since stack allocation is much cheaper than heap allocation.

Stack allocation means that, by default again, a block will cease to exist when the scope in which it is declared exits. So a block property with retain semantics will result in a dangling pointer to a block that doesn’t exist anymore when the stack gets popped.

But How?

To move a block from the stack to the heap (and thus give it normal Objective-C memory management semantics and an extended lifetime), you must copy the block via [theBlock copy], Block_copy(theBlock), property copy, using GCD via dispatch_ which copies your block, etc. Once on the heap, the block’s lifetime is managed.

That’s why you need to declare block properties with copy so the block is copied when the property is set. Thus, avoiding a dangling pointer to a stack-based block.

Therefore, if you want to access the block(s) later they have to be copied to the heap by sending a copy message to the block object. ARC will do this for you as soon as it detects a block needs to be accessed outside the scope its created in.

Behind the scene, block implementation consist of a data structure containing the values of the variables used in the block. What this means is that if you declared non-local variables will be in the data structure. Thus when you use those non-local variables, you are using the ones you’ve added onto the data structure.

For example if you have a string literal “ricky”, or a int 5, the block will create these non-local variables unto its own data structure. Thus every block has its own data structures, and contains its own non-local variables.

You can see an example here

In addition, when you have a pointer to an Object allocated on the heap, that data structure adds a new pointer, and that new pointer points to the same object in the heap.

block-2

Code

For further info, please read Block Basics

Retain Cycle on Blocks

consider this piece of code in a UIViewController. Basically, the UIViewController has a strong reference to a TapBlockView object.

Once we use self within the block, TapBlockView object then has a strong reference back to the UIViewController. Thus, the 2 objects both have a strong reference to each other…creating a retain cycle.

The reason why is because whenever a block uses a non-local variable (in our case, self), it deep copies the reference. Since self is a pointer to the UIViewController object, the block deep-copies the self pointer variable and places it in its data structure. The deep copied pointer strongly points to the UIViewController that’s in the heap.

Thus, now you have 2 situations which results in retain cycle:

1) you have a strong pointer in the block’s data structure pointing to the self object in the heap.
2) By using tapBlockView (or self.tapBlockView), UIViewController strongs it. Remember, by default, Even if you don’t use self.——, the default behavior for variables is __strong.

Solution

First, let’s set the solution up with this tidibit: Whatever pointer variable you declare INSIDE of the block, that means it gets pushed onto the local stack of the block.

Thus when the block is done, that local stack gets popped. Thus, if we were to use a strong reference and point it to whatever, when the block’s local stack gets popped, that strong reference will be nil-ed.

Part 1 – Use a weak reference to self. The weak reference promises that this block will not hold onto self. Basically, a __weak pointer will be put into the block’s data structure to be pointed to self. If and when self gets dealloc-ed, this block will not be holding on to it.

BUT! What if right we’re using the block, and the self object gets de-allocated?

Our block will be accessing bad data because we only have a weak reference to self. So in order to hold onto self just long enough for our block to do its processing….

Part 2 – our trick is to create a local strong reference to hold onto the weak reference that’s on the block’s data structure. Local strong reference pointers simply gets pushed onto the block’s local stack frame.

That way, when the block starts to process, there’s a strong reference to the self object. Hence self will never be dealloc’ed. Once the block finishes, its local stack will be popped, and thus, the strong reference will be nil-ed. Therefore, the block will only have a weak reference in its data structure that points to self. As a result, self can be dealloc’ed because there is no strong reference to it.

The main idea here, is to get a local strong pointer, and point it to a non-local weak pointer.
This accomplish 2 things:

1) The non-local weak pointer to the self variable (which gets deep copied onto the block’s data structure), prevents a retain cycle

2) The local strong reference to that weak pointer, prevents the self object from being deallocated before or during our block’s usage.

Delegate retain cycle in iOS

http://stackoverflow.com/questions/11168916/weak-or-strong-for-iboutlet-and-other

When a parent has a reference to a child object, you should use a strong reference. When a child has a reference to its parent object, you should use a weak reference or a unsafe_unretained one (if the former is not available). A typical scenario is when you deal with delegates.

First, let’s set up a protocol called TaskDelegate. It basically is a protocol for a parent, guardian, or whatever person that is in charge of taking care of the child. We require the guardian to be able to feed the child and bathe it.

MyProtocol.h

Second, we create a Child Object with a delegate that strong references a class (Parent, Guardian,…etc) that conforms to the protocol TaskDelegate. Hence we use id because we don’t know whether it will be Parent class or Guardian class or CareTaker class or whatever. As long as it conforms to the Protocol, then we’re fine. See //1

We have methods that represents the action of the Child. Specifically, the child gets hungry. We represent that by the method gotHungry.

When that action happens, gotHungry checks to see if the delegating class of either Parent, or Guardian, or CareTaker, or whomever, can respond to the method feedIt. This method should feed our Child. If it does, then we call it. See //2

Child.h

Child.m

So create a class called Parent. This Parent conforms to protocol, so hence it can take care of the Child. It creates that Child object in its init method using a strong reference. This is standard..just like how in UIViewController’s viewDidLoad, you’d often see UI objects being created, then assigning that UI’s delegate to self…which then the UIViewController must conform to.

In the same way, our Parent creates a Child object. Assigns the Child delegate to self because it conforms to the Child’s delegate.

Parent.h

Parent.m

1) Finally we are able to use our delegate. We have a Parent who creates (or strong references a Child Object) in its init method.

2) When the child got hungry, it delegates a task to the Parent object. Then you’ll see that the Parent feeds it.

3) Let’s say the Parent needs to take a vacation from this program of taking care of its kid and leaves. So we nil the parent, and ARC garbage collects it. Because the Child’s delegate is weak, it will then be set to nil when the Parent Object gets deallocated.

4) you’ll see that the Child’s delegate then will be set to nil. It can be set to another Object that conforms to TaskDelegate later…such as if we decide to create a Nanny or Guardian object so that they can feed or bathe the Child.

main.m

Result:

2015-09-11 10:12:34.144 RetainCycleEx[68141:1785252] Child.m (init) – init
2015-09-11 10:12:34.145 RetainCycleEx[68141:1785252] Parent.m (init) – init
2015-09-11 10:13:05.141 RetainCycleEx[68141:1785252] Child.m – I’m HUNGRY! whoever is taking care of this child (delegate) gots to feed it!
2015-09-11 10:13:05.141 RetainCycleEx[68141:1785252] Child.m – Yup, this guardian (or parent) can feed
2015-09-11 10:13:05.142 RetainCycleEx[68141:1785252] Parent.m – shoves baby food into child’s mouth
2015-09-11 10:13:06.012 RetainCycleEx[68141:1785252] Parent.m – I’m dealloc…
2015-09-11 10:13:06.759 RetainCycleEx[68141:1785252] Child object’s delegate 0x0
2015-09-11 10:13:08.956 RetainCycleEx[68141:1785252] Child.m – I’m dealloc..
(lldb)

The delegate Retain Cycle!!

main.m

In order to create a retain cycle, the Child object can changes it delegate from weak to strong like so:

Thus, when we run main.m we create a Child, assigns the Child to a Parent, Child gets hungry, Parent feeds it. Very standard.

When the Parent gets niled, ARC doesn’t send dealloc to Parent because child’s delegate is strong and is referencing the Parent. And because Parent is not dealloc’ed, then it will never nil the objects that it may own. In our case, the parent strong references the Child and own it, thus, it will never dealloc that Child.

Hence, the Child and Parent both do not get dealloc’ed and thus is forever floating in memory.

That’s why when you run the code, you’ll see that the dealloc of Parent is never called and thus Child’s dealloc will never be called…and that the Child’s delegate to its Parent still shows a valid Object address.:

2015-09-11 10:41:51.695 RetainCycleEx[69880:1794099] Child.m (init) – init
2015-09-11 10:41:51.696 RetainCycleEx[69880:1794099] Parent.m (init) – init
2015-09-11 10:41:54.587 RetainCycleEx[69880:1794099] Child.m – I’m HUNGRY! whoever is taking care of this child (delegate) gots to feed it!
2015-09-11 10:41:54.587 RetainCycleEx[69880:1794099] Child.m – Yup, this guardian (or parent) can feed
2015-09-11 10:41:54.587 RetainCycleEx[69880:1794099] Parent.m – shoves baby food into child’s mouth
2015-09-11 10:41:55.659 RetainCycleEx[69880:1794099] Child object’s delegate 0x1003003d0

Retain cycle in Parent Child inheritance example

Note: ARC is enabled to demonstrate strong/weak usage of retain cycle

Parent Child example

Parent.h

Parent.m

Child.h

Child.m

main.m

So we have a Parent object that has strong reference to a child Object. Upon initialization, it creates a strong reference to the child object. When we alloc and nil out the object in main, we see the appropriate actions taken:

Result:

2015-09-10 16:28:07.667 RetainCycleEx[37844:1585148] Parent.m (init) – init
2015-09-10 16:28:07.668 RetainCycleEx[37844:1585148] Child.m (init) – init
2015-09-10 16:28:07.669 RetainCycleEx[37844:1585148] Parent.m – I’m dealloc…..my retain count is 0
2015-09-10 16:28:07.669 RetainCycleEx[37844:1585148] Child.m – I’m dealloc…..my retain count is 0

Once we allocate the Parent, it in turn allocates the Child. Once we nil out the Parent, ARC garbage collects Parent object, which calls dealloc. That dealloc will set the Child object to nil, which makes ARC call Child’s dealloc so it can clean up.

Hence, everything is as expected.

Creating the retain cycle

main.m

Say we make the Child object have a strong reference on its parent. Thus, we’ve created a circular retain cycle. When fumu gets niled, the ARC won’t garbage collect it (aka call dealloc on Parent object) because Parent is pointed to by the child. If Parent’s dealloc method do not get called, then its child object won’t get niled, and thus, the Child object will never be cleaned up. Hence this parent and its child is now floating around and ARC will never clean them up because they have a strong reference towards each other.

Result:

2015-09-10 16:36:07.856 RetainCycleEx[38356:1588472] Parent.m (init) – init
2015-09-10 16:36:07.857 RetainCycleEx[38356:1588472] Child.m (init) – init

Where the problem lies
Child.h

The problem is that our Child object’s parent pointer, is a strong reference. If you change it to weak, and run the problem again, then the dealloc gets called.

The reason is because when pointer fumu gets niled, ARC will see NO strong references on Parent, thus, it will assume its safe to garbage collect it.

Result:

2015-09-10 16:46:56.921 RetainCycleEx[39034:1592492] Parent.m (init) – init
2015-09-10 16:46:56.922 RetainCycleEx[39034:1592492] Child.m (init) – init
2015-09-10 16:46:56.922 RetainCycleEx[39034:1592492] Child.m – I’m dealloc…..my retain count is 0
2015-09-10 16:46:56.923 RetainCycleEx[39034:1592492] Parent.m – I’m dealloc…..my retain count is 0

Non Propety example

We can also use __strong and __weak to demonstrate this. Notice that we must be in an ARC environment in order to see the effects of __strong/__weak.

We first create a pointer fumu to a Parent object. Even though no __strong is specified, it is by default __strong. Then we have a weak reference to the same Parent object. we set the fumu to nil.

At this point, even though the reference fumu is niled in the auto varaibles console, you’ll see that strongFumu and weakFumu are pointing to an object with an address. That’s because we still have a strong reference to the Parent object pointing to by strongFumu.

Then we nil out strongFumu and you’ll see both weakFumu and strongFumu both being niled. That’s because the Parent object have 0 strong references on it. Thus ARC garbage collects it and Parent object’s dealloc method gets called.

//3

2015-09-10 17:04:49.289 RetainCycleEx[40294:1601178] Parent.m (init) – init
2015-09-10 17:04:49.290 RetainCycleEx[40294:1601178] Child.m (init) – init

//4

2015-09-10 17:04:49.289 RetainCycleEx[40294:1601178] Parent.m (init) – init
2015-09-10 17:04:49.290 RetainCycleEx[40294:1601178] Child.m (init) – init
2015-09-10 17:04:52.383 RetainCycleEx[40294:1601178] Parent.m – I’m dealloc…
2015-09-10 17:04:52.383 RetainCycleEx[40294:1601178] Child.m – I’m dealloc..