нераспознанный селектор отправлен на экземпляр ... Ссылка на исходный код внутри - PullRequest
0 голосов
/ 09 августа 2010

Я схожу с ума от этого моего маленького приложения ... Пожалуйста, помогите мне !!!

это исходный код приложения: Smoking.zip

Сохраняет файл .dat только с NSMutableArray. Теперь, когда вы впервые запустите приложение, попробуйте иногда нажать кнопку сигареты: все должно работать нормально. Хорошо, теперь закройте приложение, снова откройте его и снова нажмите кнопку. На этот раз приложение завершится с ошибкой «нераспознанный селектор отправлен в экземпляр 0x5d18d60». Я был уверен, что проблема была в сохранении данных, потому что, когда я прокомментировал строку "[theData writeToFile: dataFilePath atomically: YES];" в методе «saveData» ошибка исчезла. Позже я обнаружил, что оно появляется снова, если я пытаюсь прочитать данные из NSMutableArray.

Пожалуйста, найдите время, чтобы проверить мой проект и помочь мне, потому что я схожу с ума от этого !!

Вот код:

#import "SmokingAppDelegate.h"
#import "SmokingViewController.h"
#import "Cig.h"

@implementation SmokingAppDelegate

@synthesize window;
@synthesize viewController, dataFilePath, smokeArray;


#pragma mark -
#pragma mark Application lifecycle

- (id) init {

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *path = [documentsDirectory stringByAppendingPathComponent:@"a.dat"];

    [self setDataFilePath:path];

    NSFileManager *fileManager = [NSFileManager defaultManager];
    if([fileManager fileExistsAtPath:dataFilePath]

       ) {
        //open it and read it 
        NSLog(@"data file found. reading into memory");

        smokeArray = [[NSMutableArray alloc] init];

        NSMutableData *theData;
        NSKeyedUnarchiver *decoder;
        NSMutableArray *tempArray;

        theData = [NSData dataWithContentsOfFile:dataFilePath];
        decoder = [[NSKeyedUnarchiver alloc] initForReadingWithData:theData];
        tempArray = [decoder decodeObjectForKey:@"smokeArray"];
        [self setSmokeArray:tempArray];

        [decoder finishDecoding];
        [decoder release];      
    } else {
        NSLog(@"no file found. creating empty array");

        smokeArray = [[NSMutableArray alloc] init];
        [smokeArray insertObject:[[NSNumber alloc] initWithInt:0] atIndex:0];

    }

//  [self logArrayContents];

    return self;
}

- (void) logArrayContents {

    for(int j = 1; j < [smokeArray count]; j++) {
        int f = [[[smokeArray objectAtIndex:j] num] intValue];
        NSLog(@"%i. - %d", j, f);
    }
}

- (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.
    [window addSubview:viewController.view];
    [window makeKeyAndVisible];

    return YES;
}



-(void) saveData {
    NSMutableData *theData;
    NSKeyedArchiver *encoder;

    theData = [NSMutableData data];
    encoder = [[NSKeyedArchiver alloc] initForWritingWithMutableData:theData];

    [encoder encodeObject:smokeArray forKey:@"smokeArray"];

    [encoder finishEncoding];

    [theData writeToFile:dataFilePath atomically:YES];
    [encoder release];
    NSLog(@"Saved");
}

#pragma mark -
#pragma mark Memory management


- (void)dealloc {
    [viewController release];
    [window release];
    [dataFilePath release];
    [smokeArray release];
    [super dealloc];
}


@end



#import "SmokingViewController.h"
#import "SmokingAppDelegate.h"
#import "Cig.h"

@implementation SmokingViewController
@synthesize label;

- (void)viewDidLoad {
[super viewDidLoad];

    SmokingAppDelegate *mainDelegate = (SmokingAppDelegate *)[[UIApplication sharedApplication] delegate];

//controlla se il giorno è lo stesso rispetto a quello dell'ultima sigaretta fumata
    if ([mainDelegate.smokeArray count] > 1) {


        Cig *oldCig = [mainDelegate.smokeArray lastObject];
        NSArray *tempArray = [self quando];

        if (    [[tempArray objectAtIndex:0] intValue]==[[oldCig.dat objectAtIndex:0] intValue]
            &&  [[tempArray objectAtIndex:1] intValue]==[[oldCig.dat objectAtIndex:1] intValue]
            &&  [[tempArray objectAtIndex:2] intValue]==[[oldCig.dat objectAtIndex:2] intValue]
            ) {
            N = [oldCig.num intValue];
        }
        else {
            N = 0;
        }

        [oldCig release];
        [tempArray release];

 }


//scrive quante sigarette si sono fumate oggi
    label.text = [NSString stringWithFormat: @"Today you smoked %d cigarettes",N];




}

- (IBAction) smoke:(UIButton * ) button {

    SmokingAppDelegate *mainDelegate = (SmokingAppDelegate *)[[UIApplication sharedApplication] delegate];
    NSLog(@"L'array contiene %d sigarette", [mainDelegate.smokeArray count]-1);

    N += 1;

    [self addNewCigToArray];
    [mainDelegate logArrayContents];
    [mainDelegate saveData];

    label.text = [NSString stringWithFormat: @"Today you smoked %d cigarettes",N];


}


- (void) addNewCigToArray {

    //NSLog(@"new cigarette smoked");
    SmokingAppDelegate *mainDelegate = (SmokingAppDelegate *)[[UIApplication sharedApplication] delegate];
    Cig *newCig = [[Cig alloc] init]; 

    [newCig setDat:[self quando]]; 
    [newCig setNum:[[NSNumber alloc] initWithInt:N]];

    [mainDelegate.smokeArray addObject:newCig]; 
    [newCig release];
    //[mainDelegate logArrayContents];

}

- (NSArray *) quando {

    NSDateFormatter *timeFormat = [[NSDateFormatter alloc] init];   

    // 0 - Year
    [timeFormat setDateFormat:@"YYYY"];
    NSString *year = [timeFormat stringFromDate:[NSDate date]];

    // 1 - Month
    [timeFormat setDateFormat:@"MM"];
    NSString *month = [timeFormat stringFromDate:[NSDate date]];

    // 2 - Day
    [timeFormat setDateFormat:@"dd"];
    NSString *day = [timeFormat stringFromDate:[NSDate date]];

    // 3 - Hour 
    [timeFormat setDateFormat:@"HH"];
    NSString *hour = [timeFormat stringFromDate:[NSDate date]];

    // 4 - Minute
    [timeFormat setDateFormat:@"mm"];
    NSString *min = [timeFormat stringFromDate:[NSDate date]];

    // 5 - Second
    [timeFormat setDateFormat:@"ss"];
    NSString *sec = [timeFormat stringFromDate:[NSDate date]];

    NSArray *newArray = [[NSArray alloc] initWithObjects:year,month,day,hour,min,sec,nil];

    return newArray;

}


- (void)viewDidUnload {
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}


- (void)dealloc {
    [super dealloc];
}

@end

1 Ответ

0 голосов
/ 10 августа 2010

Хорошо, я новичок на iPhone, поэтому примите мое предложение с ходу. Вы можете попробовать создать объект NSData, инициализировать его с помощью DataData и затем вызвать writeToFile для нового объекта NSData вместо объекта NSMutableData.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...