tailieunhanh - iOS 5 Programming Cookbook phần 2

Bây giờ nếu bạn chạy ứng dụng của bạn trên giả lập, bạn sẽ thấy một màn hình màu đen. Lý do là bộ điều khiển của chúng tôi xem xem không có một màu nền nhưng để đi đến các tập tin và tìm ra phương pháp viewDidLoad đó là ở trong tình trạng tương tự như sau: | NSLog @ Array @ array if array respondsToSelector @selector sortUsingComparator Use the sortUsingComparator instance method of the array to sort it else if array respondsToSelector @selector sortUsingFunction context Use the sortUsingFunction context instance method of the array to sort else Do something else Fantastic. We checked the existence of instance methods. How about class methods The NSArray class again has various class methods two of which are the arrayWithOb jects and the arrayWithObjects count methods. We can determine their availability at run-time and use them to initialize the array NSArray array nil if NSArray respondsToSelector @selector arrayWithObjects count NSString strings 4 strings 0 @ String 1 strings 1 @ String 2 strings 2 @ String 3 strings 3 @ String 4 array NSArray arrayWithObjects strings count 4 else if NSArray respondsToSelector @selector arrayWithObjects array NSArray arrayWithObjects @ String 1 @ String 2 @ String 3 @ String 4 nil else Do something else NSLog @ Array @ array See Also XXX Determining Whether Instance or Class Methods are Available 73 Determining Whether a Class is Available at Run Time Problem You are using a few classes that are available in the latest SDK but you are unsure whether they are available on devices that will be running your app because your deployment target is earlier than the latest SDK. Solution Use the NSClassFromString function. Pass the name of your class to this method as a string. If the return value of this function is nil that class is not available on the device that runs your app otherwise that class is available on the device and you can go ahead and use it as you wish. Here is an example if NSClassFromString @ NSJSONSerialization nil You can use this class NSJSONSerialization JSONObjectWithData . Put data here options . Put options here error . Handle errors here else That class is not available Discussion It s no secret that users are slow in upgrading their operating systems.