【发布时间】:2011-04-14 05:59:21
【问题描述】:
我有一个通过 iPhone 应用程序使用的用户类,这是我的用户类(NSobject 的子类)中的 init 和 initWithUser 函数,当我使用 initWithUser 函数时,我收到代码后描述的警告。请指教。
// serialize.h
#import <Foundation/Foundation.h>
@protocol Serialize
// serialize the object to an xml string
-(NSString*)ToXML;
@end
// user.h
#import <Foundation/Foundation.h>
#import "Serialize.h"
#import "Contact.h"
@interface User : NSObject <Serialize> {
NSString *email;
NSString *firstName;
NSString *lastName;
NSString *userId;
NSString *userName;
NSString *password;
NSMutableArray *contactList;
}
@property (nonatomic,copy) NSString *email;
@property (nonatomic,copy) NSString *firstName;
@property (nonatomic,copy) NSString *lastName;
@property (nonatomic,copy) NSString *userId;
@property (nonatomic,copy) NSString *userName;
@property (nonatomic,copy) NSString *password;
@property (nonatomic, retain) NSMutableArray *contactList;
//-(id)init;
-(id)initWithUser:(User *)copyUser;
@end
// user.m
#import "user.h"
@implementation User
@synthesize email;
@synthesize firstName;
@synthesize lastName;
@synthesize userId;
@synthesize userName;
@synthesize password;
@synthesize contactList;
-(id)init
{
// call init in parent and assign to self
if( (self = [super init]) )
{
// do something specific
contactList = [[NSMutableArray alloc] init];
}
return self;
}
-(id)initWithUser:(User *)copyUser
{
if( (self = [self init]) ) {
email = copyUser.email;
firstName = copyUser.firstName;
lastName = copyUser.lastName;
userId = copyUser.userId;
userName = copyUser.userName;
password = copyUser.password;
// release contactList initialized in the init
[contactList release];
contactList = [copyUser.contactList mutableCopy];
}
return self;
}
- (void)dealloc
{
// TODO:
[contactList removeAllObjects];
[contactList release];
[super dealloc];
}
// implementation of serialize protocol
-(NSString*)ToXML
{
return @"";
}
我在主控制器中这样使用它
- (void) registerNewUser {
RegistrationViewController *regController = [[RegistrationViewController alloc] init] ;
regController.newUser = [[User alloc] initWithUser:self.user];
[self.navigationController pushViewController:regController animated:YES];
[regController release];
}
一行
regController.newUser = [[User alloc] initWithUser:self.user];
给我以下错误,这几天让我发疯:
不兼容的 Objective-c 类型 'struct User*',当从不同的 Objective-c 类型传递 'initWithUser:' 的参数 1 时需要 'struct NSString *'
感谢任何帮助和指导
【问题讨论】:
-
嗯。你能发布
User.h文件吗? -
Serialize看起来像什么?你有什么奇怪的NSObject类别吗?任何可能涉及的#define? -
我在上面添加了序列化代码,没有#define或类似的东西
-
确实很奇怪,我得到了同样的错误,但只是将
initWithUser:方法重命名为initWithAUser:会使警告消失。尽管即使使用原始名称,它也会在运行时调用正确的方法。 -
一些后续说明:在这里重用
-init是多余的。像email这样的ivar 赋值应该是copy或retain。[contactList removeAllObjects]是多余的。最后,如前所述,newUser被过度保留,必须在调用属性设置器后释放实例。
标签: objective-c ios4