简体   繁体   English

Objective-c 指针

[英]Objective-c pointers

I don't know how to delete pointer but not an object, for example: I have some class:我不知道如何删除指针但不是 object,例如:我有一些 class:

@interface model : NSObject {
NSMutableArray *tab;
}

And when I do this:当我这样做时:

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

I want to delete only a pointer to my tab which is *tab2, but when I'm releasing tab2, tab is releasing too.我只想删除指向我的选项卡 *tab2 的指针,但是当我释放 tab2 时,选项卡也在释放。 In c++ when I'm clearing I do this:在 c++ 中,当我清除时,我这样做:

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.变量 a 仍在 memory 中,没关系。 What should I do in obj-c to delete only a pointer?我应该在 obj-c 中做什么来只删除一个指针?

In your situation with Objective-C, there's no reason to delete the pointer.在您使用 Objective-C 的情况下,没有理由删除指针。 Just let it fall out of scope.让它从 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.您只是在创建另一个指向原始选项卡 object 的指针。 If you like, you can set tab2 = nil but it doesn't really matter either way.如果你愿意,你可以设置tab2 = nil但不管怎样都无所谓。

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!在您的第二个 C++ 示例中,我不确定,但您可能会陷入未定义的行为,因为您提供的代码示例实际上适用于您测试的编译器! It is not valid C++ to delete a pointer not created with new .删除不是用new创建的指针是无效的 C++ 。

tab2 = nil; tab2 = 无; No sort of release or delete is necessary.不需要任何形式的释放或删除。 See basic memory management in iOS docs.请参阅 iOS 文档中的基本 memory 管理。 You only need to worry about objects and releasing them when you have used either new, alloc, retain, or copy.当您使用 new、alloc、retain 或 copy 时,您只需要担心对象和释放它们。

In objective-c if you do not call alloc,copy,new or retain an object, then you do not need to release it.在 objective-c 中,如果不调用 alloc、copy、new 或保留 object,则不需要释放它。 If you want to create a pointer that you can get rid of then you probably want to make a copy of the object.如果您想创建一个可以摆脱的指针,那么您可能需要制作 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.然后你可以在完成后释放 tab2 并且 tab1 仍然存在。

Hope this makes sense.希望这是有道理的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM