2013-05-14 3 views
0

Следующая ситуация:Объект стал nil после просмотра появится

У меня 2 просмотра. На первом просмотре я отображу данные о событиях, на втором я могу редактировать эти данные. Если я переключусь на мое второе представление и отредактирую значение и вернусь к первому виду, все будет работать так, как должно. Но если я не изменю эти данные и вернусь назад, то объект Event is nil будет равен нулю.

Забавная часть: до того, как я переключусь на свое второе представление, пользователь может решить (UIActionSheet), какие изменения он внесет (имя и т. Д.). На этом этапе я регистрирую этот объект и его нуль. Но на моем viewWillAppear - его второй раз, когда вид загружается - объект НЕ нуль.

Я изменил атрибут свойства моего объекта события для (сильного, неатомического), поэтому, когда я не то изменить объект все еще существует ..

я представлю некоторый код, как только им дом, но, может быть, у вас уже есть идея ..

FirstView

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    // Do any additional setup after loading the view from its nib. 


    [ADVThemeManager customizeView:self.view]; 

    [self initViewData]; 
    [self editViewStyles]; 
} 

- (void)viewWillAppear:(BOOL)animated{ 
    [super viewWillAppear:YES]; 
    NSLog(@"VIEW WILL APPEAR!!"); 
    NSLog(@"Eventname: %@", eventObject.name); 
    NSLog(@"USERID: %@", appUser.userID); 
// Logs proves that at second load of view the object is NOT nil!!! But Check ->  - (void)eventOptionSheet!! 
    [self initViewData]; 
} 

- (void) initViewData{ 
    self.invitedUserList.delegate = self; 
    self.invitedUserList.dataSource = self; 

    self.acceptedUserList.delegate = self; 
    self.acceptedUserList.dataSource = self; 

    dccon = [[DCConnector alloc]init]; 


    NSLog(@"Eventname: %@", eventObject.name); 
    NSLog(@"USERID: %@", appUser.userID); 

    invitedUsers = [NSMutableArray arrayWithArray:[eventObject.invitedUsers allObjects]]; 
    acceptedUsers = [NSMutableArray arrayWithArray:[eventObject.acceptedUsers allObjects]]; 

    eventDescriptionField.text = eventObject.descrptn; 

    NSString *eventImageName = [NSString stringWithFormat:@"%@_%@", eventObject.name, eventObject.date]; 

    if ([UtilitieHandler checkIfFileExistsWitchExstensio:eventImageName :@"png"]) { 
     [eventImage setBackgroundImage:[UtilitieHandler loadImage:[NSString stringWithFormat:@"%@.png", eventImageName]] forState:UIControlStateNormal]; 
    } 

    // Replace titleView 
    CGRect headerTitleSubtitleFrame = CGRectMake(0, 0, 200, 44); 
    UIView* _headerTitleSubtitleView = [[UILabel alloc] initWithFrame:headerTitleSubtitleFrame]; 
    _headerTitleSubtitleView.backgroundColor = [UIColor clearColor]; 
    _headerTitleSubtitleView.autoresizesSubviews = YES; 

    CGRect titleFrame = CGRectMake(0, 2, 200, 24); 
    UILabel *titleView = [[UILabel alloc] initWithFrame:titleFrame]; 
    titleView.backgroundColor = [UIColor clearColor]; 
    titleView.textColor = [UIColor colorWithRed:0.98f green:0.96f blue:0.94f alpha:1.00f]; 
    titleView.font = [UIFont fontWithName:@"OpenSans-Semibold" size:16]; 
    titleView.textAlignment = UITextAlignmentCenter; 
    titleView.shadowColor = [UIColor darkGrayColor]; 
    titleView.shadowOffset = CGSizeMake(0, -1); 
    titleView.text = eventObject.name; 
    titleView.adjustsFontSizeToFitWidth = NO; 
    [_headerTitleSubtitleView addSubview:titleView]; 

    CGRect subtitleFrame = CGRectMake(0, 24, 200, 44-24); 
    UILabel *subtitleView = [[UILabel alloc] initWithFrame:subtitleFrame]; 
    subtitleView.backgroundColor = [UIColor clearColor]; 
    subtitleView.textColor = [UIColor colorWithRed:0.98f green:0.96f blue:0.94f alpha:1.00f]; 
    subtitleView.font = [UIFont fontWithName:@"OpenSans-SemiboldItalic" size:12]; 
    subtitleView.textAlignment = UITextAlignmentCenter; 
    subtitleView.shadowColor = [UIColor darkGrayColor]; 
    subtitleView.shadowOffset = CGSizeMake(0, -1); 
    subtitleView.text = [NSString stringWithFormat:@"by %@", eventObject.createdBy.displayName]; 
    subtitleView.adjustsFontSizeToFitWidth = NO; 
    [_headerTitleSubtitleView addSubview:subtitleView]; 

    self.navigationItem.titleView = _headerTitleSubtitleView; 


    self.imageBackground.image = [[UIImage imageNamed:@"Content_Box_Small.png"] resizableImageWithCapInsets:UIEdgeInsetsMake(10, 10, 10, 10)]; 


    self.navigationController.navigationBar.layer.shadowOpacity =0.0f; 
    self.invitedUserList.backgroundColor = [UIColor clearColor]; 
    self.acceptedUserList.backgroundColor = [UIColor clearColor]; 



    // init location to map 
    CLLocationCoordinate2D coord; 
    coord.latitude = [eventObject.locLatitude doubleValue]; 
    coord.longitude = [eventObject.locLongitude doubleValue]; 

    MKCoordinateSpan span = {.latitudeDelta = 0.005, .longitudeDelta = 0.005}; 
    MKCoordinateRegion region = {coord, span}; 

    MKPointAnnotation *annotation = [[MKPointAnnotation alloc] init]; 
    annotation.coordinate = coord; 

    [eventLocation setRegion:region]; 
    [eventLocation selectAnnotation:annotation animated:YES]; 

    //add gesture to map 
    UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] 
               initWithTarget:self 
               action:@selector(navigateMe)]; 
    longPress.minimumPressDuration = 0; 
    [eventLocation addGestureRecognizer:longPress]; 

    //add right navbar item that handles invites, setting and more... 
    UIBarButtonItem *settingsItem = [[UIBarButtonItem alloc]initWithTitle:@"" style:UIBarButtonItemStylePlain target:self action:@selector(eventOptionSheet)]; 
    settingsItem.image = [UIImage imageNamed:@"navigation-btn-settings"]; 
    [settingsItem setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys: [UIFont fontWithName:@"OpenSans-Semibold" size:12], UITextAttributeFont,nil] forState:UIControlStateNormal]; 

    [self.navigationItem setRightBarButtonItem:settingsItem]; 

} 

- (void)eventOptionSheet{ 
    NSLog(@"CREATOR USER ID: %@", eventObject.createdBy.userID); 
    NSLog(@"APP USER ID: %@", appUser.userID); 

//On my second view load I probably want change more so i touch my navbar item and it leads me to this method. But here the logs are null(nil). If Change something on my seconde view this works fine again!! 

    if ([eventObject.createdBy.userID isEqualToString:appUser.userID]) { 
     eventCreatorSheet = [[UIActionSheet alloc] initWithTitle:eventObject.name delegate:self 
               cancelButtonTitle:@"Cancel" 
              destructiveButtonTitle:@"Delete Event" 
               otherButtonTitles: @"Change location", @"Edit description", @"Invite more Contacts", nil]; 
     eventCreatorSheet.actionSheetStyle = UIActionSheetStyleAutomatic; 
     [eventCreatorSheet showFromTabBar:self.tabBarController.tabBar]; 
    }else{ 
     NSSet *invitedSet = eventObject.invitedUsers; 
     NSSet *acceptedSet = eventObject.acceptedUsers; 

     BOOL existsInInvitedList = [[invitedSet valueForKeyPath:@"objectID"] containsObject:appUser.objectID]; 
     BOOL existsInAcceptedList = [[acceptedSet valueForKeyPath:@"objectID"] containsObject:appUser.objectID]; 


     if (existsInInvitedList) { 
      eventUserInvitedSheet = [[UIActionSheet alloc] initWithTitle:eventObject.name delegate:self 
                 cancelButtonTitle:@"Cancel" 
                destructiveButtonTitle:nil 
                 otherButtonTitles:@"Join", @"Decline", @"Chat creator", nil]; 
      eventUserInvitedSheet.actionSheetStyle = UIActionSheetStyleAutomatic; 
      [eventUserInvitedSheet showFromTabBar:self.tabBarController.tabBar]; 
     }else if (existsInAcceptedList){ 
      eventUserAcceptedSheet = [[UIActionSheet alloc] initWithTitle:eventObject.name delegate:self 
                 cancelButtonTitle:@"Cancel" 
                destructiveButtonTitle:nil 
                 otherButtonTitles:@"Revoke invite", @"Chat creator", nil]; 
      eventUserAcceptedSheet.actionSheetStyle = UIActionSheetStyleAutomatic; 
      [eventUserAcceptedSheet showFromTabBar:self.tabBarController.tabBar]; 
     } 
    } 

} 

-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex { 
    LastEventsViewController *lastEvents; 
    LocateEventViewController *locateEvent; 
    EventMembersViewController *inviteMoreMembers; 
    EventDescriptionViewController *eventDescriptionView; 
    EventDTO *updateEventDTO; 

    if (actionSheet == eventCreatorSheet) { 
     // creator sheet 
     switch (buttonIndex) { 
      case 0: 
       //Remove Event clicked 
       [dccon deleteEvent:eventObject]; 
       lastEvents = [[LastEventsViewController alloc]init]; 
       [[self navigationController]popToRootViewControllerAnimated:YES]; 
       break; 
      case 1: 
       //Edit location 
       locateEvent = [[LocateEventViewController alloc]init]; 
       updateEventDTO = [[EventDTO alloc]init]; 
       [updateEventDTO setDTOWithEntity:eventObject]; 
       locateEvent.eventDTO = updateEventDTO; 
       locateEvent.editEnabled = 1; 
       [[self navigationController]pushViewController:locateEvent animated:YES]; 
       break; 
      case 2: 
       //Edit description 
       eventDescriptionView = [[EventDescriptionViewController alloc]init]; 
       updateEventDTO = [[EventDTO alloc]init]; 
       [updateEventDTO setDTOWithEntity:eventObject]; 
       eventDescriptionView.eventDTO = updateEventDTO; 
       eventDescriptionView.editEnabled = 1; 
       [[self navigationController]pushViewController:eventDescriptionView animated:YES]; 
       break; 
      case 3: 
       //Invite more Contacts, check if numberOfInvites is < 50 
       break; 

     } 
    } 

    if (actionSheet == eventUserInvitedSheet) { 
     //member sheet 
     switch (buttonIndex) { 
      case 0: 
       //join Event clicked 
       NSLog(@"Event test: %@, appUserTest: %@", eventObject.name, appUser.userID); 

       [dccon addAcceptedUserToEvent:eventObject :appUser]; 
       invitedUsers = [NSMutableArray arrayWithArray:[eventObject.invitedUsers allObjects]]; 
       acceptedUsers = [NSMutableArray arrayWithArray:[eventObject.acceptedUsers allObjects]]; 
       [acceptedUserList reloadData]; 
       [invitedUserList reloadData]; 
       break; 
      case 1: 
       //Decline Event 
       [dccon removeInvitedUserFromEvent:eventObject :appUser]; 
       [dccon deleteEvent:eventObject]; 
       lastEvents = [[LastEventsViewController alloc]init]; 
       [[self navigationController]pushViewController:lastEvents animated:YES]; 
       break; 
      case 2: 
       //chat creator 
       break; 
     } 
    } 

    if (actionSheet == eventUserAcceptedSheet) { 
     //member sheet 
     switch (buttonIndex) { 
      case 0: 
       //leave Event clicked 
       [dccon removeAcceptedUserFromEvent:eventObject :appUser]; 
       [dccon deleteEvent:eventObject]; 
       lastEvents = [[LastEventsViewController alloc]init]; 
       [[self navigationController]pushViewController:lastEvents animated:YES]; 
       break; 
      case 1: 
       //chat creator 
       break; 
     } 
    } 

    if (actionSheet == changeImageSheet) { 
     UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init]; 
     imagePickerController.allowsEditing = YES; 

     switch (buttonIndex) { 
      case 0: 
       //Remove user clicked 
       imagePickerController.delegate = self; 
       imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera; 

       [self presentModalViewController:imagePickerController animated:YES]; 
       break; 
      case 1: 
       //Show Creator 
       imagePickerController.delegate = self; 
       imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary; 

       [self presentModalViewController:imagePickerController animated:YES]; 
       break; 
     } 
    } 
} 

Seconde Просмотр

@interface EventDescriptionViewController(){ 
    DCConnector *dccon; 
} 

@end 

@implementation EventDescriptionViewController 

@synthesize imageBackground, descriptionTextField, editEnabled, eventDTO; 

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil 
{ 
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; 
    if (self) { 
     // Custom initialization 
    } 
    return self; 
} 

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    // Do any additional setup after loading the view from its nib. 

    [ADVThemeManager customizeView:self.view]; 

    [self initViewData]; 

    [self styleViews]; 
} 

- (void) initViewData{ 
    UILabel *labelTitle = [[UILabel alloc] initWithFrame:CGRectZero]; 
    labelTitle.backgroundColor = [UIColor clearColor]; 
    labelTitle.textColor = [UIColor colorWithRed:0.98f green:0.96f blue:0.94f alpha:1.00f]; 
    labelTitle.font = [UIFont fontWithName:@"OpenSans-Semibold" size:16]; 
    labelTitle.text = @"Event description"; 
    [labelTitle sizeToFit]; 
    UIView *viewTitle = [[UIView alloc] initWithFrame:labelTitle.bounds]; 
    CGRect frameLbl = labelTitle.bounds; 
    viewTitle.frame = frameLbl; 
    [viewTitle addSubview:labelTitle]; 
    [self.navigationItem setTitleView:viewTitle]; 

    self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"background-tbl"]]; 
    self.imageBackground.image = [[UIImage imageNamed:@"Content_Box_Small.png"] resizableImageWithCapInsets:UIEdgeInsetsMake(10, 10, 10, 10)]; 


    if (editEnabled == 1) { 
     UIBarButtonItem *newEventToggleView = [[UIBarButtonItem alloc]initWithTitle:@"Save" style:UIBarButtonItemStylePlain target:self action:@selector(updateEvent)]; 
     [newEventToggleView setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys: [UIFont fontWithName:@"OpenSans-Semibold" size:12.0], UITextAttributeFont,nil] forState:UIControlStateNormal]; 

     [self.navigationItem setRightBarButtonItem:newEventToggleView]; 

     descriptionTextField.text = eventDTO.description; 

    }else{ 
     UIBarButtonItem *newEventToggleView = [[UIBarButtonItem alloc]initWithTitle:@"Next" style:UIBarButtonItemStylePlain target:self action:@selector(initNextEventView)]; 
     [newEventToggleView setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys: [UIFont fontWithName:@"OpenSans-Semibold" size:12.0], UITextAttributeFont,nil] forState:UIControlStateNormal]; 

     [self.navigationItem setRightBarButtonItem:newEventToggleView]; 

    } 


    descriptionTextField.font = [UIFont fontWithName:@"OpenSans-Semibold" size:14]; 

} 

- (void)styleViews{ 
    [self.descriptionTextField.layer setBorderWidth:2.0]; 
    [self.descriptionTextField.layer setBorderColor:[[UIColor colorWithRed:(107/255.0) green:(96/255.0) blue:(84/255.0) alpha:1.00f] CGColor]]; 

    self.descriptionTextField.layer.cornerRadius = 5; 
    self.descriptionTextField.clipsToBounds = YES; 
} 
- (void)updateEvent{ 
    eventDTO.description = self.descriptionTextField.text; 
    //Edit Event and push it to all members 
    dccon = [[DCConnector alloc]init]; 
    [dccon updateEvent:eventDTO]; 
    EventOverviewController *overview = (EventOverviewController*)[self.navigationController.viewControllers objectAtIndex:1]; 
    overview.eventObject = (Event*)[dccon getObjectWithID:eventDTO.entitysID]; 
    overview.appUser = [dccon getAppUser]; 
    [[self navigationController]popToViewController:overview animated:YES]; 

} 

FirstView .h файл

@property (strong, nonatomic) Event *eventObject; 
@property (strong, nonatomic) User *appUser; 
//Other properties 

Второй .h файл

@property (strong, nonatomic) EventDTO *eventDTO; 
@property (nonatomic, readwrite) NSInteger editEnabled; 
+0

который является типом объекта? NSString или другой? – DharaParekh

+0

В первом представлении это NSManagedObject, а во втором - пользовательский NSObject. – SaifDeen

+1

Вы говорите о UIView или UIViewController - будьте конкретны. И, пожалуйста, покажите свой код, чтобы мы могли понять вашу проблему. Ваш вопрос недостаточно описателен, чтобы понять вашу проблему. –

ответ

0

Я думаю, что проблема в том, что, когда вы возвращаетесь из вашего второй точки зрения, вы устанавливают объект с отредактированным значением и сохраняют его. Если значение не отредактировано, то этот объект будет равен нулю, и вы сохраните этот объект nil при возврате к первому виду. Если это так, то добавьте проверку состояния для nil во втором случае просмотра и сохраните данные только в том случае, если они не ноль или отредактированы.

+0

но почему это не ноль в моем взгляде? – SaifDeen

Смежные вопросы