Решение проблем совместимости IOS 4.0-5.1

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

Первая большая проблема заключается в том, что при сохранении в основные данные я использую метод ошибок, который, как я считаю, является методом ошибок Apple по умолчанию, который создается при создании базовой модели данных. Приложение просто вылетает, когда ниже 5.0, но если я заблокирую код ошибки, все работает нормально. Ниже приведен код, используемый для поиска ошибок и их обработки.

NSError *error;
if (![managedObjectContext save:&error]) { // crash here
    // This is a serious error saying the record could not be saved.
    // Advise the user to restart the application       
}

// журнал сбоев ниже

2012-05-13 10:17:22.062 PreviewMaker[41595:207] -[UIImage encodeWithCoder:]:   
unrecognized selector sent to instance 0x5e7ce80
2012-05-13 10:17:22.064 PreviewMaker[41595:207] *** Terminating app due to uncaught   
exception 'NSInvalidArgumentException', reason: '-[UIImage encodeWithCoder:]:   
unrecognized selector sent to instance 0x5e7ce80'
*** Call stack at first throw:
(
0   CoreFoundation                      0x013fc5a9 __exceptionPreprocess + 185
1   libobjc.A.dylib                     0x0178b313 objc_exception_throw + 44
2   CoreFoundation                      0x013fe0bb -[NSObject(NSObject) 
doesNotRecognizeSelector:] + 187
3   CoreFoundation                      0x0136d966 ___forwarding___ + 966
4   CoreFoundation                      0x0136d522 _CF_forwarding_prep_0 + 50
5   Foundation                          0x00c45b3e _encodeObject + 1076
6   Foundation                          0x00c50f89 +[NSKeyedArchiver 
archivedDataWithRootObject:] + 206
7   CoreData                            0x01122cb5 -[NSSQLiteConnection execute] +   
2677
8   CoreData                            0x011771d6 -[NSSQLiteConnection insertRow:] 
+ 262
9   CoreData                            0x01173e64 -[NSSQLConnection   
performAdapterOperations:] + 180
10  CoreData                            0x01173b0e -[NSSQLCore 
_performChangesWithAdapterOps:] + 494
11  CoreData                            0x011725ea -[NSSQLCore performChanges] + 410
12  CoreData                            0x0116c038 -[NSSQLCore saveChanges:] + 216
13  CoreData                            0x0112a199 -[NSSQLCore 
executeRequest:withContext:error:] + 409
14  CoreData                            0x011da70b -[NSPersistentStoreCoordinator 
executeRequest:withContext:error:] + 3691
15  CoreData                            0x01162948 -[NSManagedObjectContext save:] + 
712
16  PreviewMaker                        0x0000a0c0 -[MainViewController 
noUploadJustSaveImage:] + 331
17  PreviewMaker                        0x00009d3c -[MainViewController 
UserConfirmedToSaveImage] + 756
18  UIKit                               0x004774fd -[UIApplication 
sendAction:to:from:forEvent:] + 119
19  UIKit                               0x00507799 -[UIControl 
sendAction:to:forEvent:] + 67
20  UIKit                               0x00509c2b -[UIControl(Internal) 
_sendActionsForEvents:withEvent:] + 527
21  UIKit                               0x005087d8 -[UIControl   
touchesEnded:withEvent:] + 458
22  UIKit                               0x0049bded -[UIWindow _sendTouchesForEvent:] 
+ 567
23  UIKit                               0x0047cc37 -[UIApplication sendEvent:] + 447
24  UIKit                               0x00481f2e _UIApplicationHandleEvent + 7576
25  GraphicsServices                    0x01eb8992 PurpleEventCallback + 1550
26  CoreFoundation                      0x013dd944 
__CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__ + 52
27  CoreFoundation                      0x0133dcf7 __CFRunLoopDoSource1 + 215
28  CoreFoundation                      0x0133af83 __CFRunLoopRun + 979
29  CoreFoundation                      0x0133a840 CFRunLoopRunSpecific + 208
30  CoreFoundation                      0x0133a761 CFRunLoopRunInMode + 97
31  GraphicsServices                    0x01eb71c4 GSEventRunModal + 217
32  GraphicsServices                    0x01eb7289 GSEventRun + 115
33  UIKit                               0x00485c93 UIApplicationMain + 1160
34  PreviewMaker                        0x00002e07 main + 121
35  PreviewMaker                        0x00002d85 start + 53

)
terminate called after throwing an instance of 'NSException'

Еще одна проблема, с которой я сталкиваюсь, — установка tintColor для объектов пользовательского интерфейса, таких как UISwitch. У меня есть контроллер настроек, который имеет несколько UISwitches и такие, которые почти все имеют установленный цвет оттенка, но однажды все, что ниже 5.0, дает сбой. Как я могу справиться с двумя и не переписывать код только для совместимости с устройствами ниже 5.0.

shineSwitch = [[[UISwitch alloc] initWithFrame:CGRectZero] autorelease];
[cell.contentView addSubview:shineSwitch];
cell.accessoryView = shineSwitch;
[shineSwitch addTarget:self action:@selector(switchChanged:)  
forControlEvents:UIControlEventValueChanged];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
shineSwitch.onTintColor = [UIColor colorWithRed:0.0 green:0.61 blue:0.99 alpha:1.0]; 

// журнал сбоев ниже

2012-05-13 10:19:45.033 PreviewMaker[41611:207] -[UISwitch setOnTintColor:]: 
unrecognized selector sent to instance 0x5eab860
2012-05-13 10:19:45.034 PreviewMaker[41611:207] *** Terminating app due to uncaught   
exception 'NSInvalidArgumentException', reason: '-[UISwitch setOnTintColor:]:     
unrecognized selector sent to instance 0x5eab860'
*** Call stack at first throw:
(
0   CoreFoundation                      0x013fc5a9 __exceptionPreprocess + 185
1   libobjc.A.dylib                     0x0178b313 objc_exception_throw + 44
2   CoreFoundation                      0x013fe0bb -[NSObject(NSObject)   
doesNotRecognizeSelector:] + 187
3   CoreFoundation                      0x0136d966 ___forwarding___ + 966
4   CoreFoundation                      0x0136d522 _CF_forwarding_prep_0 + 50
5   PreviewMaker                        0x0000f6fb -[FlipsideViewController 
tableView:cellForRowAtIndexPath:] + 1353
6   UIKit                               0x004ecb98 -  
[UITableView(UITableViewInternal) _createPreparedCellForGlobalRow:withIndexPath:] + 634
7   UIKit                               0x004e24cc -
[UITableView(UITableViewInternal) _createPreparedCellForGlobalRow:] + 75
8   UIKit                               0x004f78cc -  
[UITableView(_UITableViewPrivate) _updateVisibleCellsNow:] + 1561
9   UIKit                               0x004ef90c -[UITableView layoutSubviews] +   
242
10  QuartzCore                          0x001e2a5a -[CALayer layoutSublayers] + 181
11  QuartzCore                          0x001e4ddc CALayerLayoutIfNeeded + 220
12  QuartzCore                          0x0018a0b4 
_ZN2CA7Context18commit_transactionEPNS_11TransactionE + 310
13  QuartzCore                          0x0018b294 _ZN2CA11Transaction6commitEv +  
292
14  QuartzCore                          0x0018b46d 
_ZN2CA11Transaction17observer_callbackEP19__CFRunLoopObservermPv + 99
15  CoreFoundation                      0x013dd89b 
__CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 27
16  CoreFoundation                      0x013726e7 __CFRunLoopDoObservers + 295
17  CoreFoundation                      0x0133b1d7 __CFRunLoopRun + 1575
18  CoreFoundation                      0x0133a840 CFRunLoopRunSpecific + 208
19  CoreFoundation                      0x0133a761 CFRunLoopRunInMode + 97
20  GraphicsServices                    0x01eb71c4 GSEventRunModal + 217
21  GraphicsServices                    0x01eb7289 GSEventRun + 115
22  UIKit                               0x00485c93 UIApplicationMain + 1160
23  PreviewMaker                        0x00002e07 main + 121
24  PreviewMaker                        0x00002d85 start + 53

)
terminate called after throwing an instance of 'NSException'

Любая помощь будет принята с благодарностью!


person FreeAppl3    schedule 13.05.2012    source источник
comment
Не могли бы вы предоставить журналы сбоев? Спасибо.   -  person Lorenzo B    schedule 13.05.2012
comment
Я добавил журнал сбоев... Я ценю любое предложение! Спасибо   -  person FreeAppl3    schedule 13.05.2012
comment
О первом вы можете попробовать посмотреть uiimage-encodewithcoder-urecognised-selector.   -  person Lorenzo B    schedule 13.05.2012
comment
Что касается второго, onTintColor доступен только с iOS 5. Вам нужно найти обходной путь, если он существует. Защитное программирование могло бы избежать сбоев. Например, вы используете метод respondsToSelector, если хотите проверить, может ли объект работать с определенным методом. Надеюсь, поможет.   -  person Lorenzo B    schedule 13.05.2012
comment
Спасибо, я ценю понимание. Странно, что в исключении основных данных упоминается UIImage-EncodeWithCoder, поскольку я блокирую метод ошибки, и все работает нормально. Но представление PNG может иметь какое-то отношение к этому, так что спасибо, что указали мне в этом направлении.   -  person FreeAppl3    schedule 13.05.2012