0.關於set,get方法
關於set方法
//assign
-(void)setMyObject:(id)newValue
{
_myObject = newValue;
}
//retain
-(void) setMyObject:(id)newValue
{
if(_myObject != newValue)
{
[_myObject release];
_myObject = [newValue retain];
}
}
//copy
-(void)setMyObject:(id)newValue
{
if(_myObject != newValue)
{
[_myObject release];
_myObject = [newValue copy];
}
}
1.讀取圖片
NSString *path = [[NSBundle mainBundle] pathForResource:@"icon" ofType:@"png"];
myImage = [UIImage imageWithContentsOfFile:path];
2.更改cell選中的背景
UIView *myview = [[UIView alloc] init];
myview.frame = CGRectMake(0, 0, 320, 47);
myview.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"0006.png"]];
cell.selectedBackgroundView = myview;
3.在數字鍵盤上添加button:
//定義一個消息中心
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil]; //addObserver:注冊一個觀察員 name:消息名稱
- (void)keyboardWillShow:(NSNotification *)note {
// create custom button
UIButton *doneButton = [UIButton buttonWithType:UIButtonTypeCustom];
doneButton.frame = CGRectMake(0, 163, 106, 53);
[doneButton setImage:[UIImage imageNamed:@"5.png"] forState:UIControlStateNormal];
[doneButton addTarget:self action:@selector(addRadixPoint) forControlEvents:UIControlEventTouchUpInside];
// locate keyboard view
UIWindow* tempWindow = [[[UIApplication sharedApplication] windows] objectAtIndex:1];//返回應用程序window
UIView* keyboard;
for(int i=0; i<[tempWindow.subviews count]; i++) //遍歷window上的所有subview
{
keyboard = [tempWindow.subviews objectAtIndex:i];
// keyboard view found; add the custom button to it
if([[keyboard description] hasPrefix:@"<UIKeyboard"] == YES)
[keyboard addSubview:doneButton];
}
}
4.webview從本地加載圖片
NSString *boundle = [[NSBundle mainBundle] resourcePath];
[web1 loadHTMLString:[NSString stringWithFormat:@"<img src='0001.png'/>"] baseURL:[NSURL fileURLWithPath:boundle]];
5.從網頁加載圖片並讓圖片在規定長寬中縮小
[cell.img loadHTMLString:[NSString stringWithFormat:@"<html><body><img src='%@' height='90px' width='90px'></body></html>",goodsInfo.GoodsImg] baseURL:nil];
將網頁加載到webview上通過javascript獲取里面的數據,如果只是發送了一個連接請求獲取到源碼以后可以用正則表達式進行獲取數據
NSString *javaScript1 = @"document.getElementsByName('.u').item(0).value";
NSString *javaScript2 = @"document.getElementsByName('.challenge').item(0).value";
NSString *strResult1 = [NSString stringWithString:[theWebView stringByEvaluatingJavaScriptFromString:javaScript1]];
NSString *strResult2 = [NSString stringWithString:[theWebView stringByEvaluatingJavaScriptFromString:javaScript2]];
6.用NSString怎么把UTF8轉換成unicode
utf8Str //
NSString *unicodeStr = [NSString stringWithCString:[utf8Str UTF8String] encoding:NSUnicodeStringEncoding];
7.View自己調用自己的方法:
[self performSelector:@selector(loginToNext) withObject:nil afterDelay:2];//黃色段為方法名,和延遲幾秒執行.
8.顯示圖像:
CGRect myImageRect = CGRectMake(0.0f, 0.0f, 320.0f, 109.0f);
UIImageView *myImage = [[UIImageView alloc] initWithFrame:myImageRect];
[myImage setImage:[UIImage imageNamed:@"myImage.png"]];
myImage.opaque = YES; //opaque是否透明
[self.view addSubview:myImage];
[myImage release];
WebView:
CGRect webFrame = CGRectMake(0.0, 0.0, 320.0, 460.0);
UIWebView *webView = [[UIWebView alloc] initWithFrame:webFrame];
[webView setBackgroundColor:[UIColor whiteColor]];
NSString *urlAddress = @"http://www.google.com";
NSURL *url = [NSURL URLWithString:urlAddress];
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
[webView loadRequest:requestObj];
[self addSubview:webView];
[webView release];
9.顯示網絡活動狀態指示符
這是在iPhone左上部的狀態欄顯示的轉動的圖標指示有背景發生網絡的活動。
UIApplication* app = [UIApplication sharedApplication];
app.networkActivityIndicatorVisible = YES;
10.動畫:一個接一個地顯示一系列的圖象
NSArray *myImages = [NSArray arrayWithObjects: [UIImage imageNamed:@"myImage1.png"], [UIImage imageNamed:@"myImage2.png"], [UIImage imageNamed:@"myImage3.png"], [UIImage imageNamed:@"myImage4.gif"], nil];
UIImageView *myAnimatedView = [UIImageView alloc];
[myAnimatedView initWithFrame:[self bounds]];
myAnimatedView.animationImages = myImages; //animationImages屬性返回一個存放動畫圖片的數組
myAnimatedView.animationDuration = 0.25; //瀏覽整個圖片一次所用的時間
myAnimatedView.animationRepeatCount = 0; // 0 = loops forever 動畫重復次數
[myAnimatedView startAnimating];
[self addSubview:myAnimatedView];
[myAnimatedView release];
動畫:顯示了something在屏幕上移動。注:這種類型的動畫是“開始后不處理” -你不能獲取任何有關物體在動畫中的信息(如當前的位置) 。如果您需要此信息,您會手動使用定時器去調整動畫的X和Y坐標
這個需要導入QuartzCore.framework
CABasicAnimation *theAnimation;
theAnimation=[CABasicAnimation animationWithKeyPath:@"transform.translation.x"];
//Creates and returns an CAPropertyAnimation instance for the specified key path.
//parameter:the key path of the property to be animated
theAnimation.duration=1;
theAnimation.repeatCount=2;
theAnimation.autoreverses=YES;
theAnimation.fromValue=[NSNumber numberWithFloat:0];
theAnimation.toValue=[NSNumber numberWithFloat:-60];
[view.layer addAnimation:theAnimation forKey:@"animateLayer"];
11.
Draggable items//拖動項目
Here's how to create a simple draggable image.//這是如何生成一個簡單的拖動圖象
1. Create a new class that inherits from UIImageView
@interface myDraggableImage : UIImageView { }
2. In the implementation for this new class, add the 2 methods:
- (void) touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event
{
// Retrieve the touch point 檢索接觸點
CGPoint pt = [[touches anyObject] locationInView:self];
startLocation = pt;
[[self superview] bringSubviewToFront:self];
}
- (void) touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event
{
// Move relative to the original touch point 相對以前的觸摸點進行移動
CGPoint pt = [[touches anyObject] locationInView:self];
CGRect frame = [self frame];
frame.origin.x += pt.x - startLocation.x;
frame.origin.y += pt.y - startLocation.y;
[self setFrame:frame];
}
3. Now instantiate the new class as you would any other new image and add it to your view
//實例這個新的類,放到你需要新的圖片放到你的視圖上
dragger = [[myDraggableImage alloc] initWithFrame:myDragRect];
[dragger setImage:[UIImage imageNamed:@"myImage.png"]];
[dragger setUserInteractionEnabled:YES];
12.線程:
1. Create the new thread:
[NSThread detachNewThreadSelector:@selector(myMethod) toTarget:self withObject:nil];
2. Create the method that is called by the new thread:
- (void)myMethod
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
*** code that should be run in the new thread goes here ***
[pool release];
}
//What if you need to do something to the main thread from inside your new thread (for example, show a loading //symbol)? Use performSelectorOnMainThread.
[self performSelectorOnMainThread:@selector(myMethod) withObject:nil waitUntilDone:false];
Plist files
Application-specific plist files can be stored in the Resources folder of the app bundle. When the app first launches, it should check if there is an existing plist in the user's Documents folder, and if not it should copy the plist from the app bundle.
// Look in Documents for an existing plist file
NSArray *paths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
myPlistPath = [documentsDirectory stringByAppendingPathComponent:
[NSString stringWithFormat: @"%@.plist", plistName] ];
[myPlistPath retain];
// If it's not there, copy it from the bundle
NSFileManager *fileManger = [NSFileManager defaultManager];
if ( ![fileManger fileExistsAtPath:myPlistPath] )
{
NSString *pathToSettingsInBundle = [[NSBundle mainBundle] pathForResource:plistName ofType:@"plist"];
}
//Now read the plist file from Documents
NSArray *paths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectoryPath = [paths objectAtIndex:0];
NSString *path = [documentsDirectoryPath stringByAppendingPathComponent:@"myApp.plist"];
NSMutableDictionary *plist = [NSDictionary dictionaryWithContentsOfFile: path];
//Now read and set key/values
myKey = (int)[[plist valueForKey:@"myKey"] intValue];
myKey2 = (bool)[[plist valueForKey:@"myKey2"] boolValue];
[plist setValue:myKey forKey:@"myKey"];
[plist writeToFile:path atomically:YES];
Alerts
Show a simple alert with OK button.
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:
@"An Alert!" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alert show];
[alert release];
Info button
Increase the touchable area on the Info button, so it's easier to press.
CGRect newInfoButtonRect = CGRectMake(infoButton.frame.origin.x-25, infoButton.frame.origin.y-25, infoButton.frame.size.width+50, infoButton.frame.size.height+50);
[infoButton setFrame:newInfoButtonRect];
Detecting Subviews
You can loop through subviews of an existing view. This works especially well if you use the "tag" property on your views.
for (UIImageView *anImage in [self.view subviews])
{
if (anImage.tag == 1)
{ // do something }
}
13.按住command+alt鍵,拖動,可創建快捷方式。
14.UITableViewCell選 中的自定義樣式
1.改變UITableViewCell選中時背景色
cell.selectedBackgroundView = [[[UIView alloc] initWithFrame:cell.frame] autorelease];
cell.selectedBackgroundView.backgroundColor = [UIColor xxxxxx];
2.自定義UITableViewCell選中時背景
cell.selectedBackgroundView = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"cellart.png"]] autorelease];
還有字體顏色
cell.textLabel.highlightedTextColor = [UIColor xxxcolor];
15.完全刪除xcode
sudo tmutil disablelocal
sudo /Developer/Library/uninstall-devtools --mode=all
sudo /Developer-3.2.2/Library/uninstall-devtools --mode=all
sudo tmutil enablelocal
16.lion下顯示隱藏文件夾
1 |
chflags nohidden ~/Library |
如果想隱藏:
1 |
chflags hidden ~/Library
|
17.獲取根目錄
NSString *homeDir = NSHomeDirectory();
獲取Document目錄
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDir = [paths objectAtIndex:0];
獲取caches
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
獲取臨時目錄
NSString *tmpDir = NSTemporaryDirectory();
18.ASIHttpRequest的連接重用關閉:
[requestsetShouldAttemptPersistentConnection:NO];
19.UISearchBar去背景
seachBar=[[UISearchBar alloc] init];
//修改搜索框背景
seachBar.backgroundColor=[UIColor clearColor];
//去掉搜索框背景
//1.
[[searchbar.subviews objectAtIndex:0]removeFromSuperview];
//2.
for (UIView *subview in seachBar.subviews)
{
if ([subview isKindOfClass:NSClassFromString(@"UISearchBarBackground")])
{
[subview removeFromSuperview];
break;
}
}
//3自定義背景
UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"40-di.png"]];
[mySearchBar insertSubview:imageView atIndex:1];
[imageView release];
//4輸入搜索文字時隱藏搜索按鈕,清空時顯示
- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar {
searchBar.showsScopeBar = YES;
[searchBar sizeToFit];
[searchBar setShowsCancelButton:YES animated:YES];
return YES;
}
- (BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar {
searchBar.showsScopeBar = NO;
[searchBar sizeToFit];
[searchBar setShowsCancelButton:NO animated:YES];
return YES;
}
//改變搜索按鈕文字
//改變UISearchBar取消按鈕字體
for(id cc in [searchBar subviews])
{
if([cc isKindOfClass:[UIButton class]])
{
UIButton *btn = (UIButton *)cc;
[btn setTitle:@"搜索" forState:UIControlStateNormal];
}
}
20.解決xcode4不能打開幫助文檔
1. preferences->downloads->documentation->check and install now 不過不一定起作用 如果不起作用就參考下面的方法
2. 選中iOS 5.0 Library 然后點列表左下角的向上箭頭 然后把feed的地址復制到safari里可以找到相應的library包 把它下下來(xar文件) 然后在terminal里用"xar -xf 文件名"解壓縮得到docset文件 把這個文件復制到installed location指示的位置替換掉原文件 最后把這個文件(包括其內部文件)的owner改成devdocs 再把group改成wheel 重啟xcode就行
21.動態獲取鍵盤高度
- (void) registerForKeyboardNotifications{
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWasShown:) name:UIKeyboardDidShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWasHidden:) name:UIKeyboardDidHideNotification object:nil];
}
- (void) keyboardWasShown:(NSNotification *) notif{
NSDictionary *info = [notif userInfo];
NSValue *value = [info objectForKey:UIKeyboardBoundsUserInfoKey];
CGSize keyboardSize = [value CGRectValue].size;
CGRect scrollViewFrame= [scrollView frame];
scrollViewFrame.size.height -= keyboardSize.height;
scrollView.frame = scrollViewFrame;
[scrollView scrollRectToVisible:inputElementFrame animated:YES];
keyboardWasShown = YES;
}
22.獲取mac地址
#include <sys/socket.h>
#include <sys/sysctl.h>
#include <net/if.h>
#include <net/if_dl.h>
- (NSString *)getMacAddress
{
int mgmtInfoBase[6];
char *msgBuffer = NULL;
size_t length;
unsigned char macAddress[6];
struct if_msghdr *interfaceMsgStruct;
struct sockaddr_dl *socketStruct;
NSString *errorFlag = NULL;
// Setup the management Information Base (mib)
mgmtInfoBase[0] = CTL_NET; // Request network subsystem
mgmtInfoBase[1] = AF_ROUTE; // Routing table info
mgmtInfoBase[2] = 0;
mgmtInfoBase[3] = AF_LINK; // Request link layer information
mgmtInfoBase[4] = NET_RT_IFLIST; // Request all configured interfaces
// With all configured interfaces requested, get handle index
if ((mgmtInfoBase[5] = if_nametoindex("en0")) == 0)
errorFlag = @"if_nametoindex failure";
else
{
// Get the size of the data available (store in len)
if (sysctl(mgmtInfoBase, 6, NULL, &length, NULL, 0) < 0)
errorFlag = @"sysctl mgmtInfoBase failure";
else
{
// Alloc memory based on above call
if ((msgBuffer = malloc(length)) == NULL)
errorFlag = @"buffer allocation failure";
else
{
// Get system information, store in buffer
if (sysctl(mgmtInfoBase, 6, msgBuffer, &length, NULL, 0) < 0)
errorFlag = @"sysctl msgBuffer failure";
}
}
}
// Befor going any further...
if (errorFlag != NULL)
{
NSLog(@"Error: %@", errorFlag);
return errorFlag;
}
// Map msgbuffer to interface message structure
interfaceMsgStruct = (struct if_msghdr *) msgBuffer;
// Map to link-level socket structure
socketStruct = (struct sockaddr_dl *) (interfaceMsgStruct + 1);
// Copy link layer address data in socket structure to an array
memcpy(&macAddress, socketStruct->sdl_data + socketStruct->sdl_nlen, 6);
// Read from char array into a string object, into traditional Mac address format
NSString *macAddressString = [NSString stringWithFormat:@"%02X:%02X:%02X:%02X:%02X:%02X",
macAddress[0], macAddress[1], macAddress[2],
macAddress[3], macAddress[4], macAddress[5]];
NSLog(@"Mac Address: %@", macAddressString);
// Release the buffer memory
free(msgBuffer);
return macAddressString;
}
1.
2. 23 排序
(1)直接調用系統的方法排序int
NSMutableArray*array = [[NSMutableArrayalloc]init];
[arrayaddObject:[NSNumbernumberWithInt:20]];
[arrayaddObject:[NSNumbernumberWithInt:1]];
[arrayaddObject:[NSNumbernumberWithInt:4]];
NSArray *sortedArray = [arraysortedArrayUsingSelector:@selector(compare:)];
for(inti =0; i < [sortedArraycount]; i++)
{
intx = [[sortedArrayobjectAtIndex:i]intValue];
NSLog(@"######%d\n", x);
}
(2)
NSSortDescriptor* sortByA = [NSSortDescriptorsortDescriptorWithKey:@"x" ascending:NO];
[myMutableArraysortUsingDescriptors:[NSArrayarrayWithObject:sortByA]];
(3)自定義重寫方法
/*
Abstract:Constants returned by comparison functions, indicating whether a value is equal to, less than, or greater than another value.
Declaration:enumCFComparisonResult{
kCFCompareLessThan= -1,
kCFCompareEqualTo= 0,
kCFCompareGreaterThan= 1
};
*/
#import <Cocoa/Cocoa.h>
@implementation NSNumber (MySort)
- (NSComparisonResult) myCompare:(NSString *)other {
//這里可以作適當的修正后再比較
int result = ([self intValue]>>1) - ([other intValue]>>1);
//這里可以控制排序的順序和逆序
return result < 0 ? NSOrderedDescending : result > 0 ? NSOrderedAscending : NSOrderedSame;
}
@end
int main(int argc, char *argv[])
{
NSMutableArray *array = [[NSMutableArray alloc]init];
[array addObject:[NSNumber numberWithInt:20]];
[array addObject:[NSNumber numberWithInt:1]];
[array addObject:[NSNumber numberWithInt:4]];
NSArray *sortedArray = [array sortedArrayUsingSelector:@selector(myCompare:)];
for(int i = 0; i < [sortedArray count]; i++)
{
int x = [[sortedArray objectAtIndex:i]intValue];
NSLog(@"######%d\n", x);
}
}
24動態加載第三方字體
1.網上搜索字體文件(后綴名為.ttf,或.odf)
2.把字體庫導入到工程的resouce中
3.在程序viewdidload中加載一下一段代碼
NSArray *familyNames = [UIFont familyNames];
for( NSString *familyName in familyNames ){
printf( "Family: %s \n", [familyName UTF8String] );
NSArray *fontNames = [UIFont fontNamesForFamilyName:familyName];
for( NSString *fontName in fontNames ){
printf( "\tFont: %s \n", [fontName UTF8String] );
}
}
4.假如你加入的字體為微軟雅黑,這時可以在NSLog中看到MicrosoftYaHei
5.然后在你的工程的Info.plist文件中新建一行(Add Row),添加key為:UIAppFonts,類型為Array或Dictionary都行;在UIAppFonts下再建立一個鍵值對,key為:Item 0,添加Value為XXX.ttf(你字體的名字,string型),可以添加多個
6.在你的項目里要用字體的時候 xx.font = [UIFont fontWithName:@"MicrosoftYaHei" size:20.0],這樣就可以了。
25.ios系統中各種設置項的url鏈接
在代碼中調用如下代碼:
NSURL*url=[NSURL URLWithString:@"prefs:root=WIFI"];
[[UIApplication sharedApplication] openURL:url];
即可跳轉到設置頁面的對應項。
[font=]
About — prefs:root=General&path=About
Accessibility — prefs:root=General&path=ACCESSIBILITY
Airplane Mode On — prefs:root=AIRPLANE_MODE
Auto-Lock — prefs:root=General&path=AUTOLOCK
Brightness — prefs:root=Brightness
Bluetooth — prefs:root=General&path=Bluetooth
Date & Time — prefs:root=General&path=DATE_AND_TIME
FaceTime — prefs:root=FACETIME
General — prefs:root=General
Keyboard — prefs:root=General&path=Keyboard
iCloud — prefs:root=CASTLE
iCloud Storage & Backup — prefs:root=CASTLE&path=STORAGE_AND_BACKUP
International — prefs:root=General&path=INTERNATIONAL
Location Services — prefs:root=LOCATION_SERVICES
Music — prefs:root=MUSIC
Music Equalizer — prefs:root=MUSIC&path=EQ
Music Volume Limit — prefs:root=MUSIC&path=VolumeLimit
Network — prefs:root=General&path=Network
Nike + iPod — prefs:root=NIKE_PLUS_IPOD
Notes — prefs:root=NOTES
Notification — prefs:root=NOTIFICATIONS_ID
Phone — prefs:root=Phone
Photos — prefs:root=Photos
Profile — prefs:root=General&path=ManagedConfigurationList
Reset — prefs:root=General&path=Reset
Safari — prefs:root=Safari
Siri — prefs:root=General&path=Assistant
Sounds — prefs:root=Sounds
Software Update — prefs:root=General&path=SOFTWARE_UPDATE_LINK
Store — prefs:root=STORE
Twitter — prefs:root=TWITTER
Usage — prefs:root=General&path=USAGE
VPN — prefs:root=General&path=Network/VPN
Wallpaper — prefs:root=Wallpaper
Wi-Fi — prefs:root=WIFI
prefs:root=INTERNET_TETHERING
26.取得設備進程
@interface UIDevice (ProcessesAdditions)
- (NSArray *)runningProcesses;
@end
// .m
#import <sys/sysctl.h>
@implementation UIDevice (ProcessesAdditions)
- (NSArray *)runningProcesses {
int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_ALL, 0};
size_t miblen = 4;
size_t size;
int st = sysctl(mib, miblen, NULL, &size, NULL, 0);
struct kinfo_proc * process = NULL;
struct kinfo_proc * newprocess = NULL;
do {
size += size / 10;
newprocess = realloc(process, size);
if (!newprocess){
if (process){
free(process);
}
return nil;
}
process = newprocess;
st = sysctl(mib, miblen, process, &size, NULL, 0);
} while (st == -1 && errno == ENOMEM);
if (st == 0){
if (size % sizeof(struct kinfo_proc) == 0){
int nprocess = size / sizeof(struct kinfo_proc);
if (nprocess){
NSMutableArray * array = [[NSMutableArray alloc] init];
for (int i = nprocess - 1; i >= 0; i--){
NSString * processID = [[NSString alloc] initWithFormat:@"%d", process[i].kp_proc.p_pid];
NSString * processName = [[NSString alloc] initWithFormat:@"%s", process[i].kp_proc.p_comm];
NSDictionary * dict = [[NSDictionary alloc] initWithObjects:[NSArray arrayWithObjects:processID, processName, nil]
forKeys:[NSArray arrayWithObjects:@"ProcessID", @"ProcessName", nil]];
[processID release];
[processName release];
[array addObject:dict];
[dict release];
}
free(process);
return [array autorelease];
}
}
}
return nil;
}
@end
// Example usage.
NSArray * processes = [[UIDevice currentDevice] runningProcesses];
for (NSDictionary * dict in processes){
NSLog(@"%@ - %@", [dict objectForKey:@"ProcessID"], [dict objectForKey:@"ProcessName"]);
}
27 Objective-C中isMemberOfClass&isKindOfClass的應用舉例
@interface Test : NSObject { } -(void)print; @end @implementation Tset -(void)print { printf(“This is Test.\n”); } @end
isMemberOfClass方法是來確定對象是否是某一個類的成員。 我們可以用這個方法來驗證一個特定的對象是否是一個特定的類成員。 Test *test=[Test new]; if ([test isKindOfClass: [Test class]]==YES) { Nslog(@”Test ok”); } if ([test isKindOfClass: [NSObject class]]==YES) { Nslog(@”NSObject ok”); } —– Test ok isKindOfClass方法是來確定對象是否是某一個類的成員,或者是派生自該類的成員。 isMemberOfClass和isKindOfClass之間區別是:我們可以使用isKindOfClass來確定一個對象是否是一個類的成員,或者是派生自該類的成員。 例如:我們已經成NSObject派生了自己的類,isMemberOfClass不能檢測任何的類都是基於NSObject類這一事實,而isKindOfClass可以。 Test *test=[Test new]; if ([test isKindOfClass: [Test class]]==YES) { Nslog(@”Test ok”); } if ([test isKindOfClass: [NSObject class]]==YES) { Nslog(@”NSObject ok”); } —– Test ok NSObject ok
28. 方法實現和協議遵循
NSObject還有兩個功能更加強大的內省方法,即respondsToSelector:和conformsToProtocol:。這兩個方法分別告訴您一個對象是否實現特定的方法,以及是否遵循指定的正式協議(即該對象是否采納了該協議,且實現了該協議的所有方法)。
在代碼中,您可以在類似的情況下使用這些方法。通過這些方法,您可以在將消息或消息集合發送給某些潛在的匿名對象之前,確定它們是否可以正確地進行響應。在發送消息之前進行檢查可以避免由不能識別的選擇器引起的運行時例外。在實現非正式協議(這種協議是委托技術的基礎)時,Application Kit就是在調用委托方法之前檢查委托對象是否實現該方法(通過respondsToSelector:方法)。
列表2-9顯示了如何在代碼中使用respondsToSelector:方法。
列表2-9 使用respondsToSelector:方法
- (void)doCommandBySelector:(SEL)aSelector {
|
if ([self respondsToSelector:aSelector]) {
|
[self performSelector:aSelector withObject:nil];
|
} else {
|
[_client doCommandBySelector:aSelector];
|
}
|
}
|
列表2-10顯示如何在代碼中使用conformsToProtocol:方法:
列表2-10 使用conformsToProtocol:方法
// ...
|
if (!([((id)testObject) conformsToProtocol:@protocol(NSMenuItem)])) {
|
NSLog(@"Custom MenuItem, '%@', not loaded; it must conform to the
|
'NSMenuItem' protocol.\n", [testObject class]);
|
[testObject release];
|
testObject = nil;
|
} |
29.NSstring轉wchar_t
NSStringEncoding enc = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
NSString *strName = [[NSString alloc] initWithCString:pChar encoding:enc];
NSLog(@"%@",strName);
wchar_t *pWChar = (wchar_t*)[strName cStringUsingEncoding:NSUTF32StringEncoding];
[strName release];
30.隨機數的使用
頭文件的引用
#import <time.h>
#import <mach/mach_time.h>
srandom()的使用
srandom((unsigned)(mach_absolute_time() & 0xFFFFFFFF));
直接使用 random() 來調用隨機數
31.UIImageview中旋轉圖像
float rotateAngle = M_PI;
CGAffineTransform transform =CGAffineTransformMakeRotation(rotateAngle);
imageView.transform = transform;
以上代碼旋轉imageView, 角度為rotateAngle, 方向可以自己測試哦
32.sqlite分頁
select * from tb_name limit 10 offset 1
注:limit 10 表示只顯示10行記錄,offset表示從索引號為1的記錄開始,第一行的索引號為0
33.查詢App信息
http://itunes.apple.com/lookup?id=284910350
34.自動下拉刷新
m_tableView.contentOffseta = CGPointMake(m_tableView.contentOffset.x, -65.0);
[_refreshHeaderView egoRefreshScrollViewDidEndDragging:m_tableView];
35.字符串轉化成變量名的方法
#import <objc/runtime.h>
a1 = @"This is a1";
a2 = @"This is a2";
a3 = @"This is a3";
for (int i = 0; i < 3; i++) {
NSString *var = [NSString stringWithFormat:@"a%d",i + 1];
Ivar ivar = object_getInstanceVariable(self,var.UTF8String,NULL);
NSString *str = (NSString *)object_getIvar(self, ivar);
NSLog(str);
}