【问题标题】:How to allocate memory for an array in class in objective-C?如何为objective-C中的类中的数组分配内存?
【发布时间】:2014-08-11 09:38:40
【问题描述】:

我对objective-c 非常陌生,我在这个问题上苦苦挣扎了一段时间!这是我的类原型:

@interface YoCatchModel : NSObject

/**
 Name of the Yo user. Currently this is local
 */
@property (nonatomic, strong) NSString* username;
/**
 History of the messages sent with Yo
 */
@property (nonatomic, strong, readonly) NSMutableArray* historyArray;

/*
 implement init method
 */
+ (instancetype) initmethod;

我应该在这个只读的方法中为我的历史可变数组分配内存。

我想创建另一个带有用户名字符串参数的 init 方法。这个新的 initWithUsername 方法应该在其定义中调用 init。

这是我正在尝试使用 instancetype 作为返回类型来实现 init 方法的实现。但我不太确定如何

  1. 为数组分配内存。
  2. 为用户名调用另一个 init 方法。

    @implementation YoCatchModel
    
    + (instancetype)initmethod {
        return [[[self class] alloc] init];
    }
    

如果有人能给我一些提示,我将不胜感激。到目前为止,我已经阅读了这些页面以到达这里:

http://www.techotopia.com/index.php/An_Overview_of_Objective-C_Object_Oriented_Programming#Declaring.2C_Initializing_and_Releasing_a_Class_Instance

https://developer.apple.com/library/ios/documentation/cocoa/conceptual/ProgrammingWithObjectiveC/DefiningClasses/DefiningClasses.html#//apple_ref/doc/uid/TP40011210-CH3-SW7

https://developer.apple.com/library/ios/releasenotes/ObjectiveC/ModernizationObjC/AdoptingModernObjective-C/AdoptingModernObjective-C.html#//apple_ref/doc/uid/TP40014150-CH1-SW11

【问题讨论】:

    标签: objective-c arrays memory-management


    【解决方案1】:

    initWithUsername 方法成为您的类的指定初始化程序,看起来像:

    - (instancetype)initWithUsername:(NSString *)username
    {
        self = [super init];
        if (self) {
            _username = [username copy];
            _historyArray = [NSMutableArray new];
        }
        return self;
    }
    

    您应该让默认的init 方法使用指定的初始化程序

    - (instancetype)init
    {
        return [self initWithUsername:nil];
    }
    

    请注意,此代码适用于以_ 开头的属性支持实例变量,而不是使用self.(无论如何都不适用于readonly 属性),这是为了避免可能属性设置器方法的 KVO 副作用。

    【讨论】:

    • 感谢您的回答。我想知道如何使用您的代码创建一个对象。这是我到目前为止所做的,但我得到了错误: YoCatchModel *yo; yo = [YoCatchModel 初始化];
    • 你知道我如何将参数传递给 initWithUsername
    • 你的意思是我需要同时拥有 init 和 initWithUsername 吗?
    • @Bernard 是的;同时拥有init 方法很好。你可以使用这样的东西来创建一个实例:YoCatchModel *yo = [[YoCatchModel alloc] initWithUsername:@"trojanfoe"]];.
    • 非常感谢您的回答。
    猜你喜欢
    • 2018-10-06
    • 1970-01-01
    • 2018-07-14
    • 2012-08-15
    • 2022-01-04
    • 2011-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多