在Objective C中的类方法中设置属性

时间:2014-03-03 19:30:31

标签: objective-c

这是我的第一个Objective C项目,我在创建对象的类方法中设置属性时遇到了问题。

#import <Foundation/Foundation.h>
#import "Alphabet.h"
@interface Cipher : NSObject
// Properties that define a filename, a key and an Alphabet object
@property NSString *key;
@property (strong) Alphabet * alphabet;

// This method is a class/factory method to create a Cipher object with the key
+ (id)cipherWithKey:(NSString *) key;

// The following methods encrypt and decrypt a message with the "alphabet"
- (NSString *) decryptWithDefaultAlphabet:(NSString *) message;
- (NSString *) encryptWithDefaultAlphabet: (NSString *) message;
@end

我尝试了一些不起作用的不同事情。

#import "Cipher.h"

@implementation Cipher

@synthesize key = _key;
@synthesize alphabet = _alphabet;

+ (id) cipherWithKey : (NSString *) key {
//    self.key = key;
    [Cipher setKey : key];
    return self;
}

+ (void) setKey : (NSString *) key {
    self.key = key;
}

1 个答案:

答案 0 :(得分:4)

您的班级“工厂”方法不正确。它需要使用Cipher / alloc创建init的新实例,然后设置其密钥,最后返回新创建的实例:

+ (id) cipherWithKey : (NSString *) key {
    Cipher *res = [[Cipher alloc] init];
    [res setKey : key];
    return res; // Return the newly created object, not self (which is a Class)
}

当您创建这样的工厂方法时,通常会定义匹配的init方法,如下所示:

-(id)initWithKey:(NSString *) key {
    if (self = [super init]) {
        _key = key;
    }
    return self;
}
+ (id) cipherWithKey : (NSString *) key {
    return [[Cipher alloc] initWithKey:key];
}