Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/objective-c/26.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Objective c 在目标C中的类方法中设置属性_Objective C - Fatal编程技术网

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

Objective c 在目标C中的类方法中设置属性,objective-c,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

这是我的第一个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

您的类工厂方法不正确。它需要使用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];
}

您的类工厂方法不正确。它需要使用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];
}