我的@界面中有这个
struct track currentTrack;
struct track previousTrack;
int anInt;
由于这些不是对象,所以我不必像 int* anInt 那样拥有它们,对吧? 如果设置非对象值,如整数、 bool 值等,我不必释放旧值(假设非 GC 环境)?
该结构包含对象:
typedef struct track {
NSString* theId;
NSString* title;
} *track;
我这样做正确吗?
最后,我像这样访问结构:
[currentTrack.title ...];
currentTrack.theId = @"asdf"; //LINE 1
我还手动管理结构的内存(从 setter ),如下所示:
[currentTrack.title autorelease];
currentTrack.title = [newTitle retain];
如果我正确理解垃圾收集,我应该能够放弃它并像第 1 行(上面)那样设置它?
还有垃圾回收,我不需要 dealloc 方法,对吧? 如果我使用垃圾收集,这是否意味着它只能在 OS 10.5+ 上运行?在切换到垃圾收集代码之前我还应该知道其他什么事情吗?
抱歉,问题太多。对 Objective-C 和桌面编程非常陌生。
谢谢
最佳答案
I have this in my @interface
struct track currentTrack; struct track previousTrack; int anInt;
Since these are not objects, I do not have to have them like
int* anInt
right?
这将声明一个指向存储在其他地方的 int
的指针。
And if setting non-object values like ints, boolean, etc, I do not have to release the old value right (assuming non-GC environment)?
release
是一条消息。您只能向 Cocoa(或者在某些情况下,Core Foundation)对象发送消息。
The struct contains objects:
typedef struct track { NSString* theId; NSString* title;
更准确地说,它包含指向对象的指针。
你永远不能将对象直接存储在变量中;您只能通过向类发送 alloc
消息来动态分配它,并接收指向已分配实例的指针。同样,您只能向指向对象的指针发送消息;您不能也不应该取消引用指向对象的指针。
出于这些原因,我们几乎总是省略“指向的指针”。我们谈论指针时就好像它们是对象一样,但事实上,它们不是。
} *track;
如果您想将 track
类型声明为指向 struct track
的指针,这是正确的。一般来说,这会让人们感到困惑。
Lastly, I access the struct like this:
[currentTrack.title ...]; currentTrack.theId = @"asdf"; //LINE 1
那么上一行是第 0 行? ;)
I'm also manually managing the memory (from a setter) for the struct like this:
[currentTrack.title autorelease]; currentTrack.title = [newTitle retain];
If I'm understanding the garbage collection correctly, I should be able to ditch that and just set it like LINE 1 (above)?
如果您正在使用垃圾回收,那么 autorelease
和 retain
消息将不会执行任何操作,所以是的,普通赋值和带有(无效)release 的赋值和保留消息是等效的。
我确实质疑为什么你要把这些信息放在一个结构中而不是 model object 中不过。
Also with garbage collection, I don't need a dealloc method right? If I use garbage collection does this mean it only runs on OS 10.5+? And any other thing I should know before I switch to garbage collected code?
是:阅读Garbage Collection Programming Guide 。它告诉您需要了解的一切,包括前两个问题的答案。
关于指针,你可能想阅读my pointers tutorial 。标题说的是 C,但 C 中的一切在 Objective-C 中也同样适用。
关于objective-c - 指点一下,我使用得正确吗? Objective-c/ cocoa ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2565820/