Sunday, June 14, 2015

C arrays and Objective-C ARC

I just converted a MRR (manual retain release) project into a ARC (automatic reference counting) project.

I use Xcode to help me convert the project super fast.  However, I noticed that in some of my classes there were C arrays that contained NSObject instances.  My first reaction was to say that C can not manage NSObjects, I mean how?  It isn't like NSArray where if you deallocate the NSArray it would automatically remove its reference from each of its instance.  A C array is a different beast and I could not fathom how it could "remove its reference".

So I skip it and told code to make that particular class MRR.

But curiosity got the best of me and I made a small project to see if the C array of NSObjects would deallocate with its parent class.  In short?  Yes.  The C array deallocates along with its Parent.

Here is the code that I used to test this.

@interface DHView : UIView

@end

@implementation DHView

- (void)dealloc {
NSLog(@"Dealloc: %@", self);
}

@end

@implementation dh123 {
DHView *views[3];
}

-(void)viewDidLoad {
[super viewDidLoad];
views[0] = [DHView new];
views[1] = [DHView new];
views[2] = [DHView new];
for (int i = 0; i < 3; ++i) {
NSLog(@"Create:  %@\n", views[i]);
}
}


@end


 In the viewDidLoad method of dh123ViewController, I create 3 DHViews and add it to the views property.  In the DHView I added an NSLog to the dealloc method so that I could see when it gets deallocated.  When I dismiss dh123ViewController all three DHViews deallocate.

Therefore, you should use as many C array's as your heart desires!

No comments:

Post a Comment