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="http://archive.cnblogs.com/a/2539787/0001.png" rel="nofollow"/>
5.从网页加载图片并让图片在规定长宽中缩小
[cell.img loadHTMLString:[NSString stringWithFormat:@"<html><body><img src="http://archive.cnblogs.com/a/2539787/%25@" rel="nofollow"/>
将网页加载到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 = [NSStringstringWithFormat:@"a%d",i +1];
Ivar ivar =object_getInstanceVariable(self,var.UTF8String,NULL);
NSString *str = (NSString *)object_getIvar(self, ivar);
NSLog(str);
}