我和朋友正在为iPhone创建一个纸牌游戏,在这个项目的早期阶段,我正在开发一个Deck课程和一个Card课程来跟上卡片。我想测试Deck类的shuffle方法,但是我无法在Deck类实例中显示卡的值。 Deck类有一个NSArray的Card对象,它有一个名为displayCard的方法,它使用控制台输出(printf或NSLog)显示值和套装。为了一次性显示Deck实例中的卡片,我使用了这个[deck makeObjectsPerformSelector:@selector(displayCard)]
,其中deck是Deck类中的NSArray。在Deck类内部,控制台输出上不显示任何内容。但是在测试文件中,它运行得很好。这是创建自己的NSArray的测试文件:
#import <Foundation/Foundation.h>
#import "card.h"
int main (int argc, char** argv)
{
NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
Card* two = [[Card alloc] initValue:2 withSuit:'d'];
Card* three = [[Card alloc] initValue:3 withSuit:'h'];
Card* four = [[Card alloc] initValue:4 withSuit:'c'];
NSArray* deck = [NSArray arrayWithObjects:two,three,four,nil];
//Ok, what if we release the objects in the array before they're used?
//I don't think this will work...
[two release];
[three release];
[four release];
//Ok, it works... I wonder how...
//Hmm... how will this work?
[deck makeObjectsPerformSelector:@selector(displayCard)];
//Yay! It works fine!
[pool release];
return 0;
}
这很好用,所以我围绕这个想法创建了一个初始化器,一次创建了52个卡片对象,并使用deck = [deck arrayByAddingObject:newCard]
将它们添加到NSArray中。真正的问题是我如何使用makeObjectsPerformSelector或之前/之后的东西?
答案 0 :(得分:1)
将对象添加到数组时,它会将retainCount增加1。这就是为什么释放它不会释放对象的原因。该阵列是在自动释放状态下创建的。释放池时,它会释放阵列和所有对象。您必须明白释放不等于免费。它只是减少了retainCount。只有当retainCount变为零时才会释放它。所以在你的函数之外,你必须以某种方式保留对象。
答案 1 :(得分:0)
如果您想要查看保留计数的实时和实际操作,请拨打以下内容:
int main (int argc, char** argv)
{
NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
Card* two = [[Card alloc] initValue:2 withSuit:'d'];
NSLog(@"Current retain count for the '2' Card: %ud", [two retainCount]);
Card* three = [[Card alloc] initValue:3 withSuit:'h'];
Card* four = [[Card alloc] initValue:4 withSuit:'c'];
NSArray* deck = [NSArray arrayWithObjects:two,three,four,nil];
NSLog(@"Current retain count for the '2' Card after array retains it: %ud", [two retainCount]);
[two release];
[three release];
[four release];
NSLog(@"Current retain count for the '2' Card after releasing instance: %ud", [two retainCount]);
[deck makeObjectsPerformSelector:@selector(displayCard)];
[deck release];
NSLog(@"Current retain count for the '2' Card after releasing instances within 'deck' array: %ud", [two retainCount]);
[pool release];
return 0;
}