xcode4.3.2 中 nib2objc 不可用的解决办法:
1 原因是 xcode4.3版本以后的路径不再是/Developer,通过下面的命令可以解决。 sudo xcode-select -switch /Applications/Xcode.app
2 或者sudo xcode-select -switch /Applications/Xcode.app/Contents/Developer
点击链接直接跳转到 App Store 指定应用下载页面
1 //跳转到应用页面
2 NSString *str = [NSString stringWithFormat:@"http://itunes.apple.com/us/app/id%d",appid];
3 [[UIApplication sharedApplication] openURL:[NSURL urlWithString:str]];
4
5 //跳转到评价页面
6 NSString *str = [NSString stringWithFormat: @"itms-apps://ax.itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?type=Purple+Software&id;=%d",
7 appid ];
8 [[UIApplication sharedApplication] openURL:[NSURL urlWithString:str]];
iOS本地推送
第一步:创建本地推送
// 创建一个本地推送
UILocalNotification *notification = [[[UILocalNotification alloc] init] autorelease];
//设置10秒之后
NSDate *pushDate = [NSDate dateWithTimeIntervalSinceNow:10];
if (notification != nil) {
// 设置推送时间
notification.fireDate = pushDate;
// 设置时区
notification.timeZone = [NSTimeZone defaultTimeZone];
// 设置重复间隔
notification.repeatInterval = kCFCalendarUnitDay;
// 推送声音
notification.soundName = UILocalNotificationDefaultSoundName;
// 推送内容
notification.alertBody = @"推送内容";
//显示在icon上的红色圈中的数子
notification.applicationIconBadgeNumber = 1;
//设置userinfo 方便在之后需要撤销的时候使用
NSDictionary *info = [NSDictionary dictionaryWithObject:@"name"forKey:@"key"];
notification.userInfo = info;
//添加推送到UIApplication
UIApplication *app = [UIApplication sharedApplication];
[app scheduleLocalNotification:notification];
}
第二步:接收本地推送
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification*)notification{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"iWeibo" message:notification.alertBody delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
[alert show];
// 图标上的数字减1
application.applicationIconBadgeNumber -= 1;
}
第三步:解除本地推送
// 获得 UIApplication
UIApplication *app = [UIApplication sharedApplication];
//获取本地推送数组
NSArray *localArray = [app scheduledLocalNotifications];
//声明本地通知对象
UILocalNotification *localNotification;
if (localArray) {
for (UILocalNotification *noti in localArray) {
NSDictionary *dict = noti.userInfo;
if (dict) {
NSString *inKey = [dict objectForKey:@"key"];
if ([inKey isEqualToString:@"对应的key值"]) {
if (localNotification){
[localNotification release];
localNotification = nil;
}
localNotification = [noti retain];
break;
}
}
}
//判断是否找到已经存在的相同key的推送
if (!localNotification) {
//不存在初始化
localNotification = [[UILocalNotification alloc] init];
}
if (localNotification) {
//不推送 取消推送
[app cancelLocalNotification:localNotification];
[localNotification release];
return;
}
}
通过代码设置UIButton
UIButton *Button_Login = [UIButton buttonWithType:UIButtonTypeRoundedRect]; //边框设置
Button_Login.frame = CGRectMake(143, 50, 40, 30); //位置及大小
Button_Login.backgroundColor = [UIColor clearColor];
[Button_Login setTitle:@"Login" forState:UIControlStateNormal]; //按钮的提示字
Button_Login.titleLabel.font = [UIFont fontWithName:@"helvetica" size:12]; //设置字体大小
[Button_Login setBackgroundImage:[UIImage imageNamed:@"28.png"] forState:UIControlStateNormal]; //设置背景图片
[self.view addSubview:Button_Login];
[Button_Login addTarget:self action:@selector(Login_Judge) forControlEvents:UIControlEventTouchDown]; //触发到函数Login_Judge中
获取图片的方法
建议使用该方法获取图片
NSString *imagePath = [[NSBundle mainBundle] pathForResource:@"sun" ofType:@"png"];
UIImage *image = [[UIImage alloc] initWithContentsOfFile:imagePath];
不要使用下面的方法,图片过大容易造成内存溢出
UIImage *image = [UIImage imageNamed:@"sun.png"];
打开闪光灯
- (void) turnTorchOn: (bool) on {
Class captureDeviceClass = NSClassFromString(@"AVCaptureDevice");
if (captureDeviceClass != nil) {
AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
if ([device hasTorch] && [device hasFlash]){
[device lockForConfiguration:nil];
if (on) {
[device setTorchMode:AVCaptureTorchModeOn];
[device setFlashMode:AVCaptureFlashModeOn];
torchIsOn = YES;
} else {
[device setTorchMode:AVCaptureTorchModeOff];
[device setFlashMode:AVCaptureFlashModeOff];
torchIsOn = NO;
}
[device unlockForConfiguration];
}
}
}
设置字体
label.font = [UIFont fontWithName:@"Arial-BoldItalicMT" size:24];
/*字体名如下:
Font Family: American Typewriter
Font: AmericanTypewriter
Font: AmericanTypewriter-Bold
Font Family: AppleGothic
Font: AppleGothic
Font Family: Arial
Font: ArialMT
Font: Arial-BoldMT
Font: Arial-BoldItalicMT
Font: Arial-ItalicMT
Font Family: Arial Rounded MT Bold
Font: ArialRoundedMTBold
Font Family: Arial Unicode MS
Font: ArialUnicodeMS
Font Family: Courier
Font: Courier
Font: Courier-BoldOblique
Font: Courier-Oblique
Font: Courier-Bold
Font Family: Courier New
Font: CourierNewPS-BoldMT
Font: CourierNewPS-ItalicMT
Font: CourierNewPS-BoldItalicMT
Font: CourierNewPSMT
Font Family: DB LCD Temp
Font: DBLCDTempBlack
Font Family: Georgia
Font: Georgia-Bold
Font: Georgia
Font: Georgia-BoldItalic
Font: Georgia-Italic
Font Family: Helvetica
Font: Helvetica-Oblique
Font: Helvetica-BoldOblique
Font: Helvetica
Font: Helvetica-Bold
Font Family: Helvetica Neue
Font: HelveticaNeue
Font: HelveticaNeue-Bold
Font Family: Hiragino Kaku Gothic **** W3
Font: HiraKakuProN-W3
Font Family: Hiragino Kaku Gothic **** W6
Font: HiraKakuProN-W6
Font Family: Marker Felt
Font: MarkerFelt-Thin
Font Family: STHeiti J
Font: STHeitiJ-Medium
Font: STHeitiJ-Light
Font Family: STHeiti K
Font: STHeitiK-Medium
Font: STHeitiK-Light
Font Family: STHeiti SC
Font: STHeitiSC-Medium
Font: STHeitiSC-Light
Font Family: STHeiti TC
Font: STHeitiTC-Light
Font: STHeitiTC-Medium
Font Family: Times New Roman
Font: TimesNewRomanPSMT
Font: TimesNewRomanPS-BoldMT
Font: TimesNewRomanPS-BoldItalicMT
Font: TimesNewRomanPS-ItalicMT
Font Family: Trebuchet MS
Font: TrebuchetMS-Italic
Font: TrebuchetMS
Font: Trebuchet-BoldItalic
Font: TrebuchetMS-Bold
Font Family: Verdana
Font: Verdana-Bold
Font: Verdana-BoldItalic
Font: Verdana
Font: Verdana-Italic
Font Family: Zapfino
Font: Zapfino*/
防止系统休眠
[UIApplication sharedApplication].idleTimeDisabled = YES
取消UITableViewCell时的蓝色高亮
cell.selectionStyle = UITableViewCellSelectionStyleNone;
/*Further, make sure you either don't implement -tableView:didSelectRowAtIndexPath: in your table view delegate or explicitly exclude the cells you want to have no action if you do implement it.*/
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
// A case was selected, so push into the CaseDetailViewController
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
if (![cell selectionStyle] == UITableViewCellSelectionStyleNone) {
// Handle tap code here
}
}
ios5以后本版 系统自带的json解析
- (IBAction)touchReadButton:(id)sender {
NSData *jsonData = [[NSData alloc] initWithContentsOfFile:JSON_PATH];
NSError *error = nil;
id jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingAllowFragments error:&error;];
if (jsonObject != nil && error == nil){
NSLog(@"Successfully deserialized...");
if ([jsonObject isKindOfClass:[NSDictionary class]]){
NSDictionary *deserializedDictionary = (NSDictionary *)jsonObject;
NSLog(@"Dersialized JSON Dictionary = %@", deserializedDictionary);
} else if ([jsonObject isKindOfClass:[NSArray class]]){
NSArray *deserializedArray = (NSArray *)jsonObject;
NSLog(@"Dersialized JSON Array = %@", deserializedArray);
} else {
NSLog(@"An error happened while deserializing the JSON data.");
}
}
}
网络编程 post方法
//Post 提交数据方法:
- (void)post
{
NSString *postString = [NSStringstringWithFormat:@" {\"userName\":\"%@\",\"userPass\":\"%@\",\"version\":\"1.0\"}",self.userField.text,self.passwordField.text];
NSLog(@"%@",postString);
//一般转化称UTF-8,这里服务器需要ASCII
NSData* postData = [postStringdataUsingEncoding:NSASCIIStringEncodingallowLossyConversion:YES];
NSMutableURLRequest *request = [[[NSMutableURLRequestalloc] init] autorelease];
[requestsetURL:[NSURLURLWithString:@"http://lib.wap.zol.com.cn/test/login.php"]];
[requestsetCachePolicy:NSURLRequestUseProtocolCachePolicy];
[requestsetTimeoutInterval:100.0];
[request setHTTPMethod:@"POST"];
[request setHTTPBody:postData];
// 应该是application/x-www-form-urlencoded,但对方服务器写成了appliction/x-www-form-urlencoded,告诉服务器是一个表单提交数据方式
[requestsetValue:@"appliction/x-www-form-urlencoded"forHTTPHeaderField:@"Content-Type"];
//得到提交数据的长度
NSString* len = [NSString stringWithFormat:@"%d", [postData length]];
//添加一个http包头告诉服务器数据长度是多少
[requestsetValue:len forHTTPHeaderField:@"Content-Length"];
[NSURLConnectionconnectionWithRequest:request delegate:self];
}
//POST接收数据方法:
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
NSLog(@"didReceiveResponse");
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
NSLog(@"didReceiveData");
[self.mutabledataappendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(@"connectionDidFinishLoading");
self.strUser = [[NSStringalloc]initWithData:self.mutabledataencoding:NSASCIIStringEncoding];
}
读取网络图片
- (UIImage *) getImageByURL:(NSString *) url {
return [[UIImage alloc] initWithData:
[NSData dataWithContentsOfURL:
[NSURL URLWithString:
[url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]]];
}
状态栏的样式
/*
在Info.plist文件中设置Status bar style的值。有三种样式可以设置:
1.Gray style (default)
2.Transparent black style (alpha of 0.5)
3.Opaque black style
*/
根据字体和文字计算UILabel的长度和大小
//Calculate the size necessary for the UILable
NSString *theText = @"Texting";
CGSize theStringSize = [theText sizeWithFont:font
constrainedToSize:theLabel.frame.size
lineBreakMode:theLabel.lineBreakMode];
//Adjust the size of the UILable
theLable.frame = CGRectMake(theLable.frame.origin.x,
theLable.frame.origin.y,
theStringSize.width, theStringSize.height);
theLable.text = theText;
捕捉屏幕截图
+ (UIImage *) imageFromView: (UIView *) theView
{
// Draw a view’s contents into an image context
UIGraphicsBeginImageContext(theView.frame.size);
CGContextRef context = UIGraphicsGetCurrentContext();
[theView.layer renderInContext:context];
UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return theImage;
}
十六进制颜色值变成UIColor
+ (UIColor *) colorFromHexRGB:(NSString *) inColorString
{
UIColor *result = nil;
unsigned int colorCode = 0;
unsigned char redByte, greenByte, blueByte;
if (nil != inColorString)
{
NSScanner *scanner = [NSScanner scannerWithString:inColorString];
(void) [scanner scanHexInt:&colorCode;]; // ignore error
}
redByte = (unsigned char) (colorCode >> 16);
greenByte = (unsigned char) (colorCode >> 8);
blueByte = (unsigned char) (colorCode); // masks off high bits
result = [UIColor
colorWithRed: (float)redByte / 0xff
green: (float)greenByte/ 0xff
blue: (float)blueByte / 0xff
alpha:1.0];
return result;
}
ios各个文件夹luj
//得到Document目录:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
//得到temp临时目录:
NSString *tempPath = NSTemporaryDirectory();
//得到目录上的文件地址:
NSString *文件地址 = [目录地址 stringByAppendingPathComponent:@"文件名.扩展名"];
用NSUserDefaults来存储数据
#import
@interface UserDefaultsHelper : NSObject {
}
+(NSString*)getStringForKey:(NSString*)key;
+(NSInteger)getIntForkey:(NSString*)key;
+(NSDictionary*)getDictForKey:(NSString*)key;
+(NSArray*)getArrayForKey:(NSString*)key;
+(BOOL)getBoolForKey:(NSString*)key;
+(void)setStringForKey:(NSString*)value:(NSString*)key;
+(void)setIntForKey:(NSInteger)value:(NSString*)key;
+(void)setDictForKey:(NSDictionary*)value:(NSString*)key;
+(void)setArrayForKey:(NSArray*)value:(NSString*)key;
+(void)setBoolForKey:(BOOL)value:(NSString*)key;
@end
//m文件
//
// UserDefaultsHelper.m
//
// Copyright (c) 2012 mobiledev.nl. All rights reserved.
#import "UserDefaultsHelper.h"
@implementation UserDefaultsHelper
+(NSString*)getStringForKey:(NSString*)key
{
NSString* val = @"";
NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];
if (standardUserDefaults) val = [standardUserDefaults stringForKey:key];
if (val == NULL) val = @"";
return val;
}
+(NSInteger)getIntForkey:(NSString *)key
{
NSInteger val = 0;
NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];
if (standardUserDefaults) val = [standardUserDefaults integerForKey:key];
return val;
}
+(NSDictionary*)getDictForKey:(NSString*)key
{
NSDictionary* val = nil;
NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];
if (standardUserDefaults) val = [standardUserDefaults dictionaryForKey:key];
return val;
}
+(NSArray*)getArrayForKey:(NSString*)key
{
NSArray* val = nil;
NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];
if (standardUserDefaults) val = [standardUserDefaults arrayForKey:key];
return val;
}
+(BOOL)getBoolForKey:(NSString*)key
{
BOOL val = FALSE;
NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];
if (standardUserDefaults) val = [standardUserDefaults boolForKey:key];
return val;
}
+(void)setStringForKey:(NSString*)value:(NSString*)key
{
NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];
if (standardUserDefaults)
{
[standardUserDefaults setObject:value forKey:key];
[standardUserDefaults synchronize];
}
}
+(void)setIntForKey:(NSInteger)value:(NSString*)key
{
NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];
if (standardUserDefaults)
{
[standardUserDefaults setInteger:value forKey:key];
[standardUserDefaults synchronize];
}
}
+(void)setDictForKey:(NSDictionary*)value:(NSString*)key
{
NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];
if (standardUserDefaults)
{
[standardUserDefaults setObject:value forKey:key];
[standardUserDefaults synchronize];
}
}
+(void)setArrayForKey:(NSArray*)value:(NSString*)key
{
NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];
if (standardUserDefaults)
{
[standardUserDefaults setObject:value forKey:key];
[standardUserDefaults synchronize];
}
}
+(void)setBoolForKey:(BOOL)value:(NSString*)key
{
NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];
if (standardUserDefaults)
{
[standardUserDefaults setBool:value forKey:key];
[standardUserDefaults synchronize];
}
}
@end
字符串转换成NSDate,计算与当前的时间差
NSString *dateStr=@"2013-08-13 20:28:40";//传入时间
//将传入时间转化成需要的格式
NSDateFormatter *format=[[NSDateFormatter alloc] init];
[format setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSDate *fromdate=[format dateFromString:dateStr];
NSTimeZone *fromzone = [NSTimeZone systemTimeZone];
NSInteger frominterval = [fromzone secondsFromGMTForDate: fromdate];
NSDate *fromDate = [fromdate dateByAddingTimeInterval: frominterval];
NSLog(@"fromdate=%@",fromDate);
[format release];
//获取当前时间
NSDate *date = [NSDate date];
NSTimeZone *zone = [NSTimeZone systemTimeZone];
NSInteger interval = [zone secondsFromGMTForDate: date];
NSDate *localeDate = [date dateByAddingTimeInterval: interval];
NSLog(@"enddate=%@",localeDate);
double intervalTime = [fromDate timeIntervalSinceReferenceDate] - [localeDate timeIntervalSinceReferenceDate];
long lTime = (long)intervalTime;
NSInteger iSeconds = lTime % 60;
NSInteger iMinutes = (lTime / 60) % 60;
NSInteger iHours = (lTime / 3600)$;
NSInteger iDays = lTime/60/60/24;
NSInteger iMonth = lTime/60/60/24/12;
NSInteger iYears = lTime/60/60/24/384;
NSLog(@"相差M年d月 或者 d日d时d分d秒", iYears,iMonth,iDays,iHours,iMinutes,iSeconds);
一个简单的使用 NSNotificationCenter 的代码例子
@implementation TestClass
- (void) dealloc
{
// If you don't remove yourself as an observer, the Notification Center
// will continue to try and send notification objects to the deallocated
// object.
[[NSNotificationCenter defaultCenter] removeObserver:self];
[super dealloc];
}
- (id) init
{
self = [super init];
if (!self) return nil;
// Add this instance of TestClass as an observer of the TestNotification.
// We tell the notification center to inform us of "TestNotification"
// notifications using the receiveTestNotification: selector. By
// specifying object:nil, we tell the notification center that we are not
// interested in who posted the notification. If you provided an actual
// object rather than nil, the notification center will only notify you
// when the notification was posted by that particular object.
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(receiveTestNotification:)
name:@"TestNotification"
object:nil];
return self;
}
- (void) receiveTestNotification:(NSNotification *) notification
{
// [notification name] should always be @"TestNotification"
// unless you use this method for observation of other notifications
// as well.
if ([[notification name] isEqualToString:@"TestNotification"])
NSLog (@"Successfully received the test notification!");
}
@end
//... somewhere else in another class ...
- (void) someMethod
{
// All instances of TestClass will be notified
[[NSNotificationCenter defaultCenter]
postNotificationName:@"TestNotification"
object:self];
}