我正在开发一个 iOS 应用程序,但在尝试保存数据时遇到了一些问题。
我的代码是:
图普拉乌苏里奥:
这是一个我保存用户数据的类。在这种情况下,我使用mensaje
变量,所以这里是它的代码:
//TuplaUsuario.h:
@interface TuplaUsuario : NSObject
{
NSMutableString* mensaje;
}
@property NSMutableString* mensaje;
@end
//TuplaUsuario.m:
#import "TuplaUsuario.h"
@implementation TuplaUsuario
@synthesize mensaje;
- (id)initWithString:(NSString *)identifier {
if ( self = [super init] ) {
mensaje = [[NSMutableString alloc] initWithString:identifier];
}
return self;
}
@end
网络服务:
这是我与 Web 服务进行通信的一个类。
//WebService.h:
#import "TuplaUsuario.h"
@interface WebService : NSObject {
// Some other data
NSMutableString* message;
TuplaUsuario* usuario;
}
//Declaration of methods
@end
//WebService.m:
#import "WebService.h"
#import "AppDelegate.h"
@implementation WebService
- (id)init:(NSString *)identifier {
self = [super init];
usuario = [[TuplaUsuario alloc] initWithString:@""];
return self;
}
- (void) processComplete: (BOOL)success {
[[self delegate] processSuccessful:success];
AppDelegate* myAppDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
[myAppDelegate setUsuarioActual:usuario];
}
- (void)login:(NSString *)username password:(NSString *)password
{
//Connection with Web Service
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)theData {
NSDictionary* jsonArray=[NSJSONSerialization
JSONObjectWithData:theData
options:0
error:nil];
message = [jsonArray objectForKey:@"message"];
[usuario setMensaje:message];
}
应用委托:
//AppDelegate.h:
#import <UIKit/UIKit.h>
#import "TuplaUsuario.h"
@interface AppDelegate : UIResponder <UIApplicationDelegate>
{
Boolean rememberMe;
TuplaUsuario* usuarioActual;
}
@property (strong, nonatomic) UIWindow *window;
@property (retain) TuplaUsuario* usuarioActual;
@end
//AppDelegate.m:
#import "AppDelegate.h"
@implementation AppDelegate
@synthesize usuarioActual;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
usuarioActual = [[TuplaUsuario alloc] initWithString:@""];
return YES;
}
问题
在WebService
, methodconnection didReceiveData
中,如果我打印message
变量,它具有正确的值,但如果我打印[usuario mensaje]
它,则打印(null)
.
我的错误在哪里?
解决了
问题出在我的ViewController
方法init
中WebService
。我调用了 init 而不是initWithString
:
视图控制器
- (void)viewDidLoad
{
[super viewDidLoad];
wSProtocol = [[WebService alloc] initWithString:@""]; //Variable of type WebService
}
网络服务
- (id)initWithString:(NSString *)identifier {
self = [super init];
usuario = [[TuplaUsuario alloc] initWithString:@""];
return self;
}