NSMutableArray返回null?

时间:2011-04-10 00:06:22

标签: iphone objective-c cocoa-touch

我有一个UITableView,它会填充我的NSMutableArray。这就是我在.h

中设置的方法
@interface processViewController : UIViewController <UITableViewDelegate, UITableViewDataSource> {
    NSMutableArray *processList;
}

@property (copy, readwrite) NSMutableArray *processList;

和我的.m

@synthesize processList;

-(void)viewDidLoad {
    processList = [[NSMutableArray alloc] init];
}

我在viewDidLoad上放了一个NSLog,它显示得很好。但是在我运行一个动作后,processList数组返回null。有什么想法吗?

感谢
库尔顿

编辑1:

- (void)startUploads {

// Start UIActivity in the top
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;

// Start Pool
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; 

// Display results for testing purposes (commented out)
NSArray *resultstwo = [database executeQuery:@"SELECT * FROM processes"];
for (NSDictionary *rowtwo in resultstwo) {

    // Get ID
    int getUserIDcount = 0;
    NSArray *getUserIDInfo = [database executeQuery:@"SELECT * FROM login"];
    for (NSDictionary *getUserIDRow in getUserIDInfo) {
        getUserIDcount++;
        NSString *oneUserID = [getUserIDRow valueForKey:@"id"];
        theUserID = [NSString stringWithFormat:@"%@", oneUserID];
    }

    // If theUserID exists...
    if (getUserIDcount == 0) {
        //myTimer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector: @selector(checkLogin) userInfo: nil repeats: NO];
    } else {


        // Get URL of image
        NSString *sqlImageUploadPathOne = @"./../Documents/";
        NSString *sqlImageUploadPathTwo = [rowtwo valueForKey:@"image"];
        NSString *getAlbumID = [rowtwo valueForKey:@"album"];
        NSString *sqlImageUploadPath = [NSString stringWithFormat:@"%@%@",sqlImageUploadPathOne,sqlImageUploadPathTwo];

        //testLabel.text = @"Uploading...";

        // Display Image in UIImageView (uploadImageHidden)
        UIImage *attemptImage = [UIImage imageNamed:sqlImageUploadPath];
        [uploadImageHidden setImage:attemptImage];



        // Upload to server
        NSData *imageData = UIImageJPEGRepresentation(uploadImageHidden.image, 90);
        NSString *urlStringOne = @"http://myflashpics.com/iphone_processes/upload.php?album=";
        NSString *urlStringTwo = @"&id=";
        NSString *urlString = [NSString stringWithFormat:@"%@%@%@%@",urlStringOne,getAlbumID,urlStringTwo,theUserID];

        NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
        [request setURL:[NSURL URLWithString:urlString]];
        [request setHTTPMethod:@"POST"];

        NSString *boundary = [NSString stringWithString:@"---------------------------14737809831466499882746641449"];
        NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary];
        [request addValue:contentType forHTTPHeaderField:@"Content-Type"];

        NSMutableData *body = [NSMutableData data];
        [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:[[NSString stringWithString:@"Content-Disposition: form-data; name=\"userfile\"; filename=\".jpg\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:[[NSString stringWithString:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:[NSData dataWithData:imageData]];
        [body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
        [request setHTTPBody:body];

        NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
        NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];

        //NSLog(@"%@", returnString);

        if ([returnString rangeOfString:@"yes"].location == NSNotFound) {
            // Fail
        } else {
            // Delete image if successful
            NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
            NSString *documentsDirectoryPath = [paths objectAtIndex:0];
            NSString *myFilePath = [documentsDirectoryPath stringByAppendingPathComponent:sqlImageUploadPathTwo];
            NSFileManager *fileManager = [NSFileManager defaultManager];
            [fileManager removeItemAtPath:myFilePath error:NULL];
            [database executeNonQuery:@"DELETE FROM processes WHERE image=?", sqlImageUploadPathTwo];

            // Get Photo ID
            NSArray *myWords = [returnString componentsSeparatedByString:@" "];
            NSString *photoID = [myWords objectAtIndex:1]; 
            NSString *usernameID = [myWords objectAtIndex:2]; 

            NSString *defaultName = @"Photo uploaded from the flashpics iPhone application";

            // Get Thumbnail URL
            NSString *thumbnailURLOne = @"http://myflashpics.com/users/";
            NSString *thumbnailURLTwo = @"/pictures/thumbnails/";
            NSString *thumbnailURLThree = @".jpg";
            NSString *thumbnailURL = [NSString stringWithFormat:@"%@%@%@%@%@",thumbnailURLOne,usernameID,thumbnailURLTwo,photoID,thumbnailURLThree];

            // Download thumbnail
            //NSLog(@"Downloading...");
            UIImage *image = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:thumbnailURL]]];
            //NSLog(@"%f,%f",image.size.width,image.size.height);
            NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
            //NSLog(@"%@",docDir);
            //NSLog(@"saving jpeg");
            NSString *jpegFilePath = [NSString stringWithFormat:@"%@/%@_thumbnail.jpg",docDir,photoID];
            NSData *data2 = [NSData dataWithData:UIImageJPEGRepresentation(image, 0.2f)];//1.0f = 100% quality
            [data2 writeToFile:jpegFilePath atomically:YES];
            //NSLog(@"saving image done");
            [image release];

            // Put in database
            NSString *thumbnailEnd = @"_thumbnail.jpg";
            NSString *thumbnailLocation = [NSString stringWithFormat:@"%@%@",photoID,thumbnailEnd];

            int theCount = 0;
            NSArray *getUserIDInfotoo = [database executeQuery:@"SELECT * FROM images WHERE id=?",photoID];
            for (NSDictionary *getUserIDRowtoo in getUserIDInfotoo) {
                theCount++;
            }

            if (theCount == 0) {
                [database executeNonQuery:@"INSERT INTO images (id, name, thumbnail, album) VALUES (?, ?, ?, ?)", photoID, defaultName, thumbnailLocation, getAlbumID];
            }
            //[NSThread detachNewThreadSelector:@selector(updateImages) toTarget:RootViewController withObject:nil];
            //myTimer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector: @selector(updateImages) userInfo: nil repeats: NO];
        }

        [request release];
        [returnString release];

    }

    //NSLog([rowtwo valueForKey:@"image"]);
    //NSLog([rowtwo valueForKey:@"album"]);
}


[pool release];

// Stop the UIActivity in the top bar
TableViewAppDelegate *dataCeter = (TableViewAppDelegate *)[[UIApplication sharedApplication] delegate];
if ([dataCeter.dataTen isEqualToString:@""]) {
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}
}

编辑2:

调用startUploads的地方(不同的.m)

processViewController *processTable = [[processViewController alloc] initWithNibName:@"processView.xib" bundle:nil];
[processTable startUploads];
[processTable release];

1 个答案:

答案 0 :(得分:3)

更多代码会有所帮助,但这里有一些建议:

  1. 在加载视图之前检查是否正在调用startUploads。只有在第一次访问视图时才会加载视图以添加到超级视图。

  2. 考虑在您的processList方法而不是init中初始化viewDidLoad以解决#1和b / c视图可以加载&amp;由iOS独立于viewController的生命周期卸载(取决于您显示的其他视图以及是否发生任何内存警告)。

  3. 确保您在processList中发布dealloc。如果在viewDidUnload中重新创建并加载,则只需在viewDidLoad中将其发布。

  4. 您的代码示例在调用startUploads时未显示,并且您没有向processList添加任何项目,因此很难判断上述内容是否相关。发布更多代码,我会相应地修改我的答案。

    祝你好运!

    [编辑:添加示例代码]

    您发布的代码片段不是视图控制器的完整实现,也不是与之交互的关联对象。鉴于我所看到的代码,您的应用程序设计不符合MVC(模型/视图/控制器)设计模式,我会做的事情有点不同。但是,我不想对我没见过的代码或作为开发人员的最终意图或能力做出假设。我无法为您编写应用程序,只是尝试直接帮助您解决有关为什么在startUploads操作完成后NSMutableArray属性保持为null的具体问题。考虑到这一点,以下是我对您发布的代码的编辑:

    processViewController.m - 添加以下内容:

    - (id)initWithNibNamed:(NSString *)nibName bundle:(NSBundle *)bundle {
        self = [super initWithNibNamed:nibName bundle:bundle];
        if (self) {
            processList = [[NSMutableArray alloc] init];
        }
        return self;
    }
    
    - (void)dealloc {
        self.processList = nil;
        [super dealloc];
    }
    

    different.m

    - (void)displayProcessVC {
        ProcessViewController *processVC = [[ProcessViewController alloc] initWithNibNamed:@"processView.xib" bundle:nil];
        NSLog(@"Different:displayProcessVC BEFORE STARTING UPLOAD, processList = %@", processVC.processList);
        [processVC startUploads];
        NSLog(@"Different:displayProcessVC AFTER STARTING UPLOAD, processList = %@", processVC.processList);
        // would normally present process VC here
        [processVC release];
    }
    

    希望这有帮助。