UIBarButtonItem *buttonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"back-button-whiteArrow.png"] style:UIBarButtonItemStylePlain target:self action:@selector(logoutBarBtnPressed:)];
UIBarButtonItem *fixedBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
fixedBarButtonItem.width = -15;
self.navigationItem.leftBarButtonItems = [NSArray arrayWithObjects:fixedBarButtonItem, buttonItem, nil];
複製代碼
fixedButton.width
配置離左邊的距離。
經過RestKit將數據保存到core data中,entity爲html
@interface Article : NSManagedObject
@property (nonatomic, retain) NSNumber* articleID;
@property (nonatomic, retain) NSString* title;
@property (nonatomic, retain) NSString* body;
@property (nonatomic, retain) NSDate* publicationDate;
@end
@implementation Article // We use @dynamic for the properties in Core Data
@dynamic articleID;
@dynamic title;
@dynamic body;
@dynamic publicationDate;
@end
複製代碼
設置object mappingios
RKEntityMapping* articleMapping = [RKEntityMapping mappingForEntityForName:@"Article"
inManagedObjectStore:managedObjectStore];
[articleMapping addAttributeMappingsFromDictionary:@{
@"id": @"articleID",
@"title": @"title",
@"body": @"body",
@"publication_date": @"publicationDate"
}];
articleMapping.identificationAttributes = @[ @"articleID" ];
複製代碼
其中的identificationAttributes 設置的數組中的值,就是用來判斷返回的數據是更新仍是new。算法
Author Entity數組
@interface Author : NSObject
@property (nonatomic, copy) NSString *name;
@property (nonatomic, copy) NSString *email;
@end
複製代碼
Article Entityxcode
@interface Article : NSObject
@property (nonatomic, copy) NSString *title;
@property (nonatomic, copy) NSString *body;
@property (nonatomic) Author *author;
@property (nonatomic) NSDate *publicationDate;
@end
複製代碼
添加好關係friendship緩存
// Create our new Author mapping
RKObjectMapping* authorMapping = [RKObjectMapping mappingForClass:[Author class] ];
// NOTE: When your source and destination key paths are symmetrical, you can use addAttributesFromArray: as a shortcut instead of addAttributesFromDictionary:
[authorMapping addAttributeMappingsFromArray:@[ @"name", @"email" ]];
// Now configure the Article mapping
RKObjectMapping* articleMapping = [RKObjectMapping mappingForClass:[Article class] ];
[articleMapping addAttributeMappingsFromDictionary:@{
@"title": @"title",
@"body": @"body",
@"publication_date": @"publicationDate"
}];
// Define the relationship mapping
[articleMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:@"author"
toKeyPath:@"author"
withMapping:authorMapping]];
RKResponseDescriptor *responseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:articleMapping
method:RKRequestMethodAny
pathPattern:nil keyPath:@"articles"
statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)];
複製代碼
在Json轉Model的時候,使用JTObjectMapping方法很相似。減小不少的工做量。bash
緣由: Deployment Target版本比真機版本高,致使找不到。將Deployment Target設置成與真機的系統版本一致。網絡
autoLayout 須要在- (void)viewDidLoad
方法執行完後生效,因此須要在- (void)viewDidAppear:(BOOL)animated
方法中再進行frame的獲取,此時才能取到正確的frame。app
**根據蘋果官方指出:backbarbuttonItem不能定義customview,因此,只能貼圖或者,讓leftBarButtonItem變成自定義返回按鈕,本身寫個方法進行[self.navigationController pop當前Item **ide
以前你們是否疑惑爲何設置了相似這樣的代碼
UIBarButtonItem *backButton = [[UIBarButtonItem alloc]
initWithTitle:@"返回"
style:UIBarButtonItemStylePlain
target:self
action:nil];
self.navigationItem.backBarButtonItem = backButton;
複製代碼
界面上backButton並沒出現「返回」的字樣.
實際上是被leftBarButtonItem和rightBarButtonItem的設置方法所迷惑了leftBarButtonItem和rightBarButtonItem設置的是本級頁面上的BarButtonItem,而backBarButtonItem設置的是下一級頁面上的BarButtonItem. 好比:兩個ViewController,主A和子B,咱們想在A上顯示「刷新」的右BarButton,B上的BackButton顯示爲「撤退」就應該在A的viewDidLoad相似方法中寫:
UIBarButtonItem *refreshButton = [[UIBarButtonItem alloc]
initWithTitle:@"刷新"
style:UIBarButtonItemStylePlain
target:self
action:nil];
self.navigationItem.rightBarButtonItem = refreshButton;
UIBarButtonItem *cancelButton = [[UIBarButtonItem alloc]
initWithTitle:@"撤退"
style:UIBarButtonItemStylePlain
target:self
action:nil];
self.navigationItem.backBarButtonItem = cancelButton;
複製代碼
而B不須要作任何處理而後ApushB就能夠了.
sharedClient.securityPolicy.allowInvalidCertificates = YES;
複製代碼
進行JSON轉化的時候,須要知足一下的要求。
An object that may be converted to JSON must have the following properties:
也就是說:nil,基礎數據不能轉化爲JSON。
+ (NSArray *)arrayWithObjectsExceptionNil:(id)firstObj, ...
{
NSMutableArray *tempMArray = [[NSMutableArray alloc] initWithCapacity:5];
id eachObject = nil;
va_list argumentList;
if ( firstObj ) {
[tempMArray addObject:firstObj];
va_start(argumentList, firstObj);
while ( (eachObject = va_arg(argumentList, id))){
if ( nil != eachObject ){
[tempMArray addObject:eachObject];
}
}
va_end(argumentList);
}
return nil;
}
複製代碼
NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
// app名稱
NSString *app_Name = [infoDictionary objectForKey:@"CFBundleDisplayName"];
// app版本
NSString *app_Version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
// app build版本
NSString *app_build = [infoDictionary objectForKey:@"CFBundleVersion"];
複製代碼
**注意:appid,在申請提交的時候,在itunesconnect的這個裏面生成了,審覈經過了也不會改變。 **
若是在編譯的時候找不到文件,須要先在Build Phases中的Compile Sources 將不存在的文件刪除,而後再將找不到的文件添加到project中。
你還能夠看到其餘名字打頭的一些類,好比CF、CA、CG、UI等等,好比 CFStringTokenizer 這是個分詞的東東 CALayer 這表示Core Animation的層 CGPoint 這表示一個點 UIImage 這表示iPhone裏面的圖片
CF說的是Core Foundation,CA說的是Core Animation,CG說的是Core Graphics,UI說的是iPhone的User Interface
file's owner 就是xib對應的類,如view對應的xib文件的file's owner對應的類就是viewcontroller的類。 file’s owner 是view和viewcontroller之間的對應關係的橋樑。(即,一個視圖,如何知道本身的界面的操做應該由誰來響應)
通常iOS app coin應該是不透明的,而且不能夠在app中屢次使用app coin。
自定義類庫中,須要重寫NSObject的兩個固定方法來判斷類是否重複:
- (BOOL)isEqual:(id)anObject;
- (NSUInteger)hash;
複製代碼
// Macro wrapper for NSLog only if debug mode has been enabled
#ifdef DEBUG
#define DLog(fmt,...) NSLog(fmt, ##__VA_ARGS__);
#else
// If debug mode hasn't been enabled, don't do anything when the macro is called
#define DLog(...)
#endif
#define MR_ENABLE_ACTIVE_RECORD_LOGGING 0
#define IS_OS_6_OR_LATER ([[[UIDevice currentDevice] systemVersion] floatValue] >= 6.0)
#define IS_OS_7_OR_LATER ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0)
#define OBJISNULL(o) (o == nil || [o isKindOfClass:[NSNull class]] || ([o isKindOfClass:[NSString class]] && [o length] == 0))
#define APP ((AppDelegate*)[[UIApplication sharedApplication] delegate])
#define UserDefaults [NSUserDefaults standardUserDefaults]
#define SharedApplication [UIApplication sharedApplication]
#define SYSTEM_VERSION_EQUAL_TO(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedSame)
#define SYSTEM_VERSION_GREATER_THAN(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedDescending)
#define SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending)
#define SYSTEM_VERSION_LESS_THAN(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedAscending)
#define SYSTEM_VERSION_LESS_THAN_OR_EQUAL_TO(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedDescending)
#define RGB(r, g, b) [UIColor colorWithRed:r/255.0 green:g/255.0 blue:b/255.0 alpha:1.0]
#define RGBA(r, g, b, a) [UIColor colorWithRed:r/255.0 green:g/255.0 blue:b/255.0 alpha:a]
複製代碼
#define iPhone5 ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(640, 1136), [[UIScreen mainScreen] currentMode].size) : NO)
複製代碼
說明符 | 描述 |
---|---|
%@ | Objective-c 對象 |
%zd | NSInteger |
%lx | CFIndex |
%tu | NSUInteger |
%i | int |
%u | unsigned int |
%hi | short |
%hu | unsigned short |
%% | %符號 |
NSString *s;
在非ARC 的狀況下, s指向任意地址,多是系統地址,致使崩潰。
在ARC 的狀況下,s已經自動初始化爲nil。
[_paths addObject:[_path copy]];
若是這個_path爲nil,那麼就會出現一個crash。由於在容器中不能存放nil,能夠用[NSNull null]來保存.
推薦 pod 'XTSafeCollection', '~> 1.0.4'
第三方庫,對數組的越界,賦值nil,都有保護做用。
Math中一個算法命令。 函數名: ceil用 法: double ceil(double x);功 能: 返回大於或者等於指定表達式的最小整數頭文件:math.h
float f = 1.2222;
NSLog(@"f is %f.", ceil(f));
複製代碼
打印: f is 2.000000.
函數名: floor功 能: 返回小於或者等於指定表達式的最大整數用 法: double floor(double x);頭文件:math.h
float f = 1.2222;
NSLog(@"f is %f.", floor(f));
複製代碼
打印: f is 1.000000.
在Xcode點擊工程,在工程中選擇「TARGETS」你的工程,在Build Phases中選擇「Compile Sources」,找到你須要設置非ARC的類,在這個類的右邊有一個「Compiler Flags」,在這個裏面設置「-fno-objc-arc 」。 那麼這個類就是非ARC進行編譯了。
storyboard上不能進行scrollview滾動的緣由是: autolayout引發的
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[NSThread sleepForTimeInterval:3.0f];
return YES;
}
複製代碼
在利用Xcode進行調試時,watchdog不會運行,所在設備中測試程序啓動性能時,不要將設備鏈接到Xcode。
若是你使用的是Localizable.strings,那麼你在程序中能夠這樣獲取字符串: NSLocalizedString(@"mykey", nil)
若是你使用的是自定義名字的.strings,好比MyApp.strings,那麼你在程序中能夠這樣獲取字符串: NSLocalizedStringFromTable (@"mykey",@"MyApp", nil)
這樣便可獲取到"myvalue"這個字符串,能夠是任何語言。
使用UIAppearance進行外觀的自定義。
[+ appearance]
修改整個程序中某個class的外觀
[[UINavigationBar appearance] setTintColor:myColor];
複製代碼
[+ appearanceWhenContainedIn:]
當某個class被包含在另一個class內時,才修改外觀。
[[UILabel appearanceWhenContainedIn:[cusSearchBar class], nil] setTextColor:[UIColor redColor]];
複製代碼
在使用網絡地址時,通常要先將url進行encode成UTF8格式的編碼,不然在使用時可能報告網址不存在的錯誤,這時就須要進行轉換 下面就是轉換函數:
NSString *urlString= [NSString stringWithFormat:@"http://www.baidu.com"];
NSString *encodedString = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes( kCFAllocatorDefault, (CFStringRef)urlString, NULL, NULL, kCFStringEncodingUTF8 ));
NSURL *url = [NSURL URLWithString:encodedString];
複製代碼
或者使用下面的方法:
NSString *utf8Str = @"Testing";
NSString *unicodeStr = [NSString stringWithCString:[utf8Str UTF8String] encoding:NSUnicodeStringEncoding];
複製代碼
有時候獲取的url中的中文等字符是亂碼,網頁內容是亂碼,須要進行一下轉碼才能正確識別NSString,能夠用下面的方法:
//解決亂碼問題()
NSString *transString = [NSString stringWithString:[string stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
複製代碼
NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setAMSymbol:@"AM"];
[dateFormatter setPMSymbol:@"PM"];
[dateFormatter setDateFormat:@"dd/MM/yyyy hh:mmaaa"];
NSDate *date = [NSDate date];
NSString *s = [dateFormatter stringFromDate:date];
複製代碼
顯示效果爲: 10/05/2010 03:49PM
//判斷是否爲整形:
- (BOOL)isPureInt:(NSString*)string{
NSScanner* scan = [NSScanner scannerWithString:string];
int val;
return[scan scanInt:&val] && [scan isAtEnd];
}
//判斷是否爲浮點形:
- (BOOL)isPureFloat:(NSString*)string{
NSScanner* scan = [NSScanner scannerWithString:string];
float val;
return[scan scanFloat:&val] && [scan isAtEnd];
}
if( ![self isPureInt:insertValue.text] || ![self isPureFloat:insertValue.text])
{
resultLabel.textColor = [UIColor redColor];
resultLabel.text = @"警告:含非法字符,請輸入純數字!";
return;
}
複製代碼
iOS中從程序bundle中加載UIImage通常有兩種方法。 第一種比較常見:imageNamed
第二種方法不多使用:imageWithContentsOfFile
爲何有兩種方法完成一樣的事情呢?imageNamed的優勢在於能夠緩存已經加載的圖片。蘋果的文檔中有以下說法: This method looks in the system caches for an image object with the specified name and returns that object if it exists. If a matching image object is not already in the cache, this method loads the image data from the specified file, caches it, and then returns the resulting object. 這種方法會在系統緩存中根據指定的名字尋找圖片,若是找到了就返回。若是沒有在緩存中找到圖片,該方法會從指定的文件中加載圖片數據,並將其緩存起來,而後再把結果返回。 而imageWithContentsOfFile
方法只是簡單的加載圖片,並不會將圖片緩存起來。這兩個方法的使用方法以下:
UIImage *img = [UIImage imageNamed:@"myImage"]; // caching
// or
UIImage *img = [UIImage imageWithContentsOfFile:@"myImage"]; // no caching
複製代碼
那麼該如何選擇呢? 若是加載一張很大的圖片,而且只使用一次,那麼就不須要緩存這個圖片。這種狀況imageWithContentsOfFile比較合適——系統不會浪費內存來緩存圖片。
然而,若是在程序中常常須要重用的圖片,那麼最好是選擇imageNamed方法。這種方法能夠節省出每次都從磁盤加載圖片的時間。
根據圖片上下左右4邊的像素進行自動擴充。
UIImage *image = [UIImage imageNamed:@"png-0016"];
UIImage *newImage = [image resizableImageWithCapInsets:UIEdgeInsetsMake(50, 50, 50, 50) resizingMode:UIImageResizingModeStretch];
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(50, 50, 200, 400)];
imageView.image = newImage;
imageView.contentMode = UIViewContentModeScaleAspectFill;
複製代碼
使用方法- (UIImage *)resizableImageWithCapInsets:(UIEdgeInsets)capInsets resizingMode:(UIImageResizingMode)resizingMode NS_AVAILABLE_IOS(6_0); // the interior is resized according to the resizingMode
進行對圖片的拉伸,可使用UIImageResizingModeTile和UIImageResizingModeStretch兩種拉伸方式。 **注意: **此方法返回一個新的UIImage,須要使用這個新的image。
注:UIEdgeInsets設置的值不要上下或左右交叉,否則會出現中間爲空白的狀況。
在Xcode5中也可使用新特性 Slicing,直接對圖片進行設置,不須要在代碼中設置了。
NSData *imageData = [NSData dataWithContentsOfFile:imagePath];
UIImage *aimage = [UIImage imageWithData:imageData];
//UIImage 轉化爲 NSData
NSData *imageData = UIImagePNGRepresentation(aimage);
複製代碼
// NSDictionary -> NSData:
NSData *myData = [NSKeyedArchiver archivedDataWithRootObject:myDictionary];
// NSData -> NSDictionary:
NSDictionary *myDictionary = (NSDictionary*) [NSKeyedUnarchiver unarchiveObjectWithData:myData];
複製代碼
若是顯示的數值爲價格,則用貨幣模式
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterCurrencyStyle];
self.introView.guaranteedDataLabel.text = [formatter stringFromNumber:self.quoteEntity.guranteedInfo.guaranteedPrice];
複製代碼
CGFloat lengths[] = {5, 5};
CGContextRef content = UIGraphicsGetCurrentContext();
CGContextBeginPath(content);
CGContextSetLineWidth(content, LINE_WIDTH);
CGContextSetStrokeColorWithColor(content, [UIColor blackColor].CGColor);
CGContextSetLineDash(content, 0, lengths, 2);
CGContextMoveToPoint(content, 0, rect.size.height - LINE_WIDTH);
CGContextAddLineToPoint(content, rect.size.width, rect.size.height - LINE_WIDTH);
CGContextStrokePath(content);
CGContextClosePath(content);
複製代碼
- (BOOL)shouldAutorotate
{
return NO;
}
- (NSUInteger)supportedInterfaceOrientations {
return UIInterfaceOrientationMaskLandscapeLeft;
}
- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation {
return UIInterfaceOrientationLandscapeLeft;
}
複製代碼
在storyboard中設置只支持豎屏,能夠在單個UIViewController中加入這3個方法,使得這個UIViewController只支持左橫屏。
設置UITextField的inputView能夠不彈出鍵盤,而彈出UIDatePicker。
首先須要在View加載結束的時候指定文本的InputView
UIDatePicker *datePicker = [[UIDatePicker alloc] init];
datePicker.datePickerMode = UIDatePickerModeDate;
[datePicker addTarget:self action:@selector(dateChanged:) forControlEvents:UIControlEventValueChanged];
self.txtDate.inputView = datePicker;
複製代碼
而後須要指定當UIDatePicker變更的時候的事件是什麼. 此處就是爲了給文本框賦值.
- (IBAction)dateChanged:(id)sender
{
UIDatePicker *picker = (UIDatePicker *)sender;
self.txtDate.text = [NSString stringWithFormat:@"%@", picker.date];
}
複製代碼
而後當文本框編輯結束時, 須要讓UIDatePicker消失.
- (IBAction)doneEditing:(id)sender
{
[self.txtDate resignFirstResponder];
}
複製代碼
而後把文本框在IB中, 指向定義好的txtDate就好了~
在Info.plist中設置UIViewControllerBasedStatusBarAppearance
爲NO
在須要改變狀態欄顏色的ViewController中在ViewDidLoad方法中增長:
UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
複製代碼
若是須要在所有View中都變色,能夠寫在父類的相關方法中。
//會調用2次,開始時和結束時
- (void)hello:(UILongPressGestureRecognizer *)longPress
{
if (longPress.state == UIGestureRecognizerStateEnded)//須要添加一個判斷
{
NSLog(@"long");
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"hello"
message:@"Long Press"
delegate:self
cancelButtonTitle:@"OK"
otherButtonTitles:nil, nil];
[alert show];
}
}
複製代碼
self.scrollView.exclusiveTouch = YES;
複製代碼
設置exclusiveTouch這個屬性爲YES。
delaysContentTouches 屬性是UIScrollView中當即響應Touch事件。默認是YES,若是想點擊後立刻有反應,則將該值設置爲NO。
若是在UITableView上添加一個自定義的UIView,須要注意在view中的顏色會由於Cell被選中的點擊色,而引發view的顏色變化,而且不可逆。
當 NSNotificationCenter 註冊一個通知後
- (void)addObserver:(id)observer selector:(SEL)aSelector name:(nullableNSString *)aName object:(nullableid)anObject;
複製代碼
在class的dealloc中,必定要使用
- (void)removeObserver:(id)observer name:(nullable NSString *)aName object:(nullable id)anObject;
複製代碼
進行註銷。
不能用 - (void)removeObserver:(id)observer;
進行通知的註銷。
注意: 若是不註銷,將致使class不會被釋放。
H5開發的弊端: 佔用內容太多。在打開H5的時候,會佔用大量的內存,在項目中看到,通常會達到一個頁面50M的內存。
設置left bar button後,會致使右滑返回的效果失效,查看完美的設置方案。
同時爲了獲取到右滑返回的事件,能夠執行
[self.navigationController.interactivePopGestureRecognizer addTarget:self action:@selector(back)];
複製代碼
**在ViewController中viewDidAppare中添加,在viewWillDisappear中remove。 **
[self.bottomOpenStoreBtn mas_remakeConstraints:^(MASConstraintMaker *make) {
make.top.mas_equalTo(promptImageView.mas_bottom).with.offset(30);
make.height.mas_equalTo(44);
make.width.mas_equalTo(SCREEN_WIDTH - 30);
make.centerX.mas_equalTo(self.promptScrollView);
make.bottom.mas_equalTo(self.promptScrollView.mas_bottom).with.offset(-30);
}];
複製代碼
設置self.bottomOpenStoreBtn的頂部與promptImageView的頂部距離30pt make.bottom.mas_equalTo(self.promptScrollView.mas_bottom).with.offset(-30);
其中的 self.promptScrollView.mas_bottom 必須使用mas_bottom,不能使用bottom.
make.top 中的top爲 - (MASConstraint*)top
而 self.promptScrollView.bottom 中的bottom爲
- (float) bottom
{ return CGRectGetMaxY (self.frame);
}
複製代碼
即一個是layout屬性,另外一個爲frame的屬性。