iOS アプリケーションを開発していますが、データを保存しようとすると問題が発生します。
私のコードは次のとおりです。
TuplaUsuario:
ユーザーデータを保存するクラスです。その場合、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:
//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
メソッドconnection didReceiveData
ではmessage
、変数を出力すると正しい値が表示されますが、[usuario mensaje]
出力すると が出力され(null)
ます。
私のエラーはどこですか?
解決した
問題は私ViewController
のinit
方法にありWebService
ました。の代わりに init を呼び出しましたinitWithString
:
ViewController
- (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;
}