2010-12-21 34 views
1

我創建了一個新的「基於視圖的應用程序」項目,並修改瞭如下的didFinishLaunchingWithOptions:方法。在AppDelegate中加載數據,但以後在UIView中無法訪問?怎麼了?

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {  
    // Override point for customization after application launch. 
    // Add the view controller's view to the window and display. 
    [self.window addSubview:viewController.view]; 
    [self.window makeKeyAndVisible]; 
    downloader = [[InternetIOProcess alloc] init]; 
    [downloader initWithServer:[NSURL URLWithString:@"http://www.test.com"] ]; 
    return YES; 
} 

InternetIOProcess是NSObject有兩個變量,一個方法:

@interface InternetIOProcess : NSObject { 
    NSMutableArray* downloadingFile; 
    NSURL* serverAddress;} 
@property (nonatomic,retain) NSMutableArray* downloadingFile; 
@property (nonatomic,retain) NSURL* serverAddress; 
-(void) initWithServer:(NSURL*) server; 

InternetIOProcess的實現是:

@implementation InternetIOProcess 
@synthesize downloadingFile,serverAddress; //,serviceuploadingQueue,; 
-(void) initWithServer:(NSURL*) server 
{ 
    downloadingFile = [NSMutableArray array]; 
    serverAddress = server; 
} 

然後,我寫了IBActionUIViewController響應一個按鈕「touch up inside」事件:

-(IBAction) test:(id)sender 
{ 
    MyAppDelegate* d = (MyAppDelegate*)[UIApplication sharedApplication].delegate; 
    InternetIOProcess* thedownloader = d.downloader; 
    //value of "thedownloader" incorrect. 
} 

嘗試在這裏訪問「thedownloader」,其成員「downloadingFile,serverAddress」都會給出隨機的錯誤值!

有人知道我爲什麼不能訪問這個對象?

回答

2

問題在於你沒有保留init的數組和服務器以及錯誤的命名約定。它看起來像你的自定義init方法沒有被調用。

-(void) initWithServer:(NSURL*) server 
{ 
    downloadingFile = [NSMutableArray array]; 
    serverAddress = server; 
} 

嘗試做以下修改

//InternetIOProcess.h add 
-(id) initWithServer:(NSURL*) server; 

//InternetIOProcess.m change 
-(id) initWithServer:(NSURL*) server 
{ 
    self = [super init]; 
    if(self != nil) 
    { 
     downloadingFile = [[NSMutableArray array] retain]; 
     serverAddress = [server retain]; 
    } 
    return self; 
} 

//MyAppDelegate.m 
downloader = [[InternetIOProcess alloc] initWithServer:[NSURL URLWithString:@"http://www.test.com"]]; 
+0

設置保留爲NSMutableArray裏的屬性。但是,初始化程序[NSMutableArray數組]將返回一個爲autorelease設置的對象。我建議不要這樣做,而是使用語法:「[[NSMutableArray alloc] init]」。應該隱含保留。委託中的對象從不保留。 – Luke 2010-12-21 21:46:17

1

只是檢查,UIViewController中包含

#import "MyAppDelegate.h" 

#import "InternetIOProcess.h" 

而且你MyAppDelegate包含

#import "InternetIOProcess.h" 

而且,你得到任何編譯警告?

1

下載器是否具有委託類上的retain屬性?當您分配實例時,我看不到您指定保留。

1

在您的initWithServer:方法中,使用self.downloadingFile和self.serverAddress,以便保留對象。

相關問題