Search code examples
objective-ciosmemory-managementdealloc

how to properly alloc/dealloc this pointer? objective-c


*beginner iOS programmer, please explain with patience

suppose i have 2 classes - Foo, Bar

in class Bar, i have a pointer to an instance of Foo, which i set during init. (and because i dont know how to properly import Foo and Bar with each other, i end up setting the type to id instead of Foo)

@implementation Bar{
    id pointerToInstanceOfFoo;
}

how do i write my dealloc function for Bar? or DO I even override the dealloc function?

right now i have

-(void)dealloc{
    pointerToInstanceOfFoo = NULL;
    [super dealloc];
}

i still want that pointer to Foo to be around when Bar dies, but am i doing things right? several questions:

  1. if Foo and Bar imports from each other, how do i do this? or is this bad software design?
  2. right now i have the pointer "pointerToInstanceOfFoo" set in the @implementation... is this equivalent to declaring a private pointer in class Bar?
  3. should i instead be using @property (nonatomic, weak) id pointerToInstanceOfFoo instead? if so, why do i keep getting this error about no weak pointers in ARC?
  4. do i need delete pointerToInstanceOfFoo; in the dealloc function??

Sorry for the confusion, any explanations/answers would be greatly appreciated!!

P.S. i'm using XCode 4.4 and running on iOS 5.0 with cocos2d v2.1 beta... i think it's using arc


Solution

  • You are not allowed to use [super dealloc] in ARC. So if that compiles, you are not using ARC and you need cals to retain and release. Writing a whole tutorial on that is not something that will fit in a stack overflow answer. As for your other questions:

    1) Just import them in the implementation file, not the header file.

    2) Yes

    3) If it makes you happy. The error probably means you are targeting below iOS 5.0 (I.e. the deployment target in your project settings is set to less than 5.0), in which weak pointers are not supported, or ARC is turned off. I don't think you've accurately reported the error message since it makes no sense.

    4) "delete" is not valid objective-c or valid c.

    P.S. No, you don't want that pointer to be around after Bar is deallocated because that would be a memory leak. Perhaps you want a static variable instead of an instance variable?