Objective c 在目标C中的类方法中设置属性
这是我的第一个Objective 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
#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];
}