objective-c - 在分配的 UIViewController 上设置属性

标签 objective-c ios uiviewcontroller custom-controls init

我使用如下自定义初始化方法创建了一个简单的 UIViewController:

-(id)initWithGroupNumber:(NSString *)groupNumber {
if ((self = [super init]) == nil) {
    return nil;
}
self.levelGroup = groupNumber;
return self; }

levelGroup是写在.h文件中的属性

@property (nonatomic, retain) NSString  *levelGroup;

当我这样调用上面的方法时:

    LevelsViewController *lvc = [[LevelsViewController alloc]initWithGroupNumber:@"5"];

Controller 已分配,但其中的所有属性都设置为零。我不明白为什么。

最佳答案

首先,当您处理具有可变类型子类的类时(例如 NSMutableString),请使用copy

所以,你的属性(property)应该变成:

@property (nonatomic, copy) NSString *levelGroup;

然后,在 UIViewController 中合成属性

@synthesize levelGroup;

并在 init 中执行以下操作:

-(id)initWithGroupNumber:(NSString *)groupNumber {

    if (self = [super init]) {
       levelGroup = [groupNumber copy];
    }
    return self;
}

memory management guide 中所写你不应该在 initdealloc 中使用 self.

使用您的属性 self.levelGroup 获取或设置值。

记得在dealloc中释放:

[levelGroup release];

希望对您有所帮助。

关于objective-c - 在分配的 UIViewController 上设置属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9521943/

相关文章:

objective-c - Block 隐式保留 'self' ;明确提及 'self' 以表明这是预期行为

ios - 查询 HealthKit 以获取当天的总步数

objective-c - 在控制台中强制写入 Xcode 'Debugger Output'?

ios - 苹果是否允许应用程序让用户将图像发布到论坛等共享页面?

iOS - UIViewControllers 共享一个屏幕

ios - 为什么 methodLists 是指向 objc_class 中的指针的指针

ios - didUpdateLocations 未被调用

iphone - 如何在GameCenter应用程序中支持多个游戏

iOS 为所有 viewcontroller self.view 设置背景颜色

ios - 为什么 ViewController 实例的 View 仍在另一个 View 的 subview 列表中时被释放?