开发者

Objective-c pointers

I don't know how to delete pointer but not an object, for example: I have some class:

@interface model : NSObject {
NSMutableArray *tab;
}

And when I do this:

model1 = [[model alloc]init];
NSMutableArray * tab2 = [model1 tab];
...
some operations
...

I w开发者_开发知识库ant to delete only a pointer to my tab which is *tab2, but when I'm releasing tab2, tab is releasing too. In c++ when I'm clearing I do this:

int a =10;
*w = &a;

and when I'm deleting a pointer do

delete w;

and variable a is still in memory and that's is ok. What should I do in obj-c to delete only a pointer?


In your situation with Objective-C, there's no reason to delete the pointer. Just let it fall out of scope. You're not allocating any new objets. You're not making a copy of tab. You're not retaining it. You're just creating another pointer to the original tab object. If you like, you can set tab2 = nil but it doesn't really matter either way.

In your second C++ example, I'm not certain, but you're probably falling into undefined behavior because of the fact that the code example you gave actually works on the compiler you tested! It is not valid C++ to delete a pointer not created with new.


tab2 = nil; No sort of release or delete is necessary. See basic memory management in iOS docs. You only need to worry about objects and releasing them when you have used either new, alloc, retain, or copy.


In objective-c if you do not call alloc,copy,new or retain an object, then you do not need to release it. If you want to create a pointer that you can get rid of then you probably want to make a copy of the object.

NSMutableArray * tab2 = [model1 tab] copy];

or

NSMutableArray *tab2 = [model1 tab] mutableCopy];

then you can release tab2 when you're done with it and tab1 will still exist.

Hope this makes sense.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜