atomic只能保证读写的原子性,即有三个线程A,B,C 同时操作一个atomic的属性p。其中 线程A读取p值,线程B和线程C分别向p赋值。在这种情况下线程A读取的p值只可能有三种情 况,A初始值,线程B赋的值和线程C赋的值。因为,atomic保证了读写操作的原子性。但线 程A所读的值是不能确定的,所以不具备线程安全性。另外,如果出现线程D,在线程A,B, C进行读写操作的同时,释放掉属性p,则有几率会造成崩溃,也是线程不安全的情况。
atomic只能保证读写的原子性,即有三个线程A,B,C 同时操作一个atomic的属性p。其中 线程A读取p值,线程B和线程C分别向p赋值。在这种情况下线程A读取的p值只可能有三种情 况,A初始值,线程B赋的值和线程C赋的值。因为,atomic保证了读写操作的原子性。但线 程A所读的值是不能确定的,所以不具备线程安全性。另外,如果出现线程D,在线程A,B, C进行读写操作的同时,释放掉属性p,则有几率会造成崩溃,也是线程不安全的情况。
Swift类定义前加入@objc关键字,并使类继承自NSObject
@objc class S : NSObject{ func m() { print(__FUNCTION__) } }
头文件具体的名字可在 设置选项:
{project} - {targets} - {build settings} - {swift compiler - code generation} - {Objective-C Generated Interface Header Name}
#import "objc_swift-Swift.h" int main(int argc, const char * argv[]) { @autoreleasepool { S* s = [[S alloc]init]; [s m]; } return 0; }
选择Create Bridging Header
{project} - {targets} - {build settings} - {swift compiler - code generation} - {Objective-C Bridging Header}
// // Use this file to import your target's public headers that you would like to expose to Swift. // #import "O.h"
.h 文件
@interface O : NSObject -(void)m; @end
.m 文件
@implementation O -(void)m { NSLog(@"%s", __FUNCTION__); } @end
swift 文件
@objc class S : NSObject{ let o:O = O() func m() { o.m() print(__FUNCTION__) } }
accessor method accessor表示两个方法,一个叫做getter用于获取,另一个叫做setter用于设置。 getter形式为 - (type)name, setter形式为-(void)setName。 accessor method represents two method. one is getter and the other is setter. the method of getter defaults as ‘-(type)name and setter defaults as -(void)setName
@property @property 生成 instance variable 和 accessor。 @property makes instance variable (ivar) and accessor
@synthesize @synthesize与@property配对,提供将@proerty与成员变量绑定的功能,即指定@property的inistance variable为特定的成员变量。 synthesize prepairs @property.in @synthesize the ivar can bind a class member, @syntax property-name=ivar-name
atomic atomic的意思是读和写是原子操作,但是线程安全要保证同时读写数据不会出错,所以atomic无法保证。本质就是在getter和setter加入一个锁,赋值或取值前锁定,结束后解除。nonatomic/atomic 原子操作,但不能保证线程安全,默认为atomic,常用为nonatomic。 nonatomic/atomic is atomic operation. this does not gurantee the safe-thread. default value is atomic.atomic means the reading and writing are atomic each,but the safe-thread requests reading and writing in the same time do not case the problem. the atomic add the lock in getter and setter.
readonly/readwrite 读写或只读,本质就是生成getter和setter或者只生成getter readwrite makes the getter and setter and the readonly makes the only getter.
weak/strong(assgin/retaine) copy weak/strong in ARC, weak means assgin in setter, strong means reference count draining in setter(complite manages automatic reference count). assgin/reatin in MRC are deprecated now. copy means using copy in setter. weak/strong作为ARC自动引用计数时代,weak本质是setter内直接赋值,strong本质是setter时增加引用计数(引用计数由编译器,编译时增加)(assign/retain 为MRC手动引用计数时代的标志,已经被淘汰) copy 表示setter中使用copy方式
dotsyntax dotsyntax本质是转化为 getter 和 setter dotsyntax means sending getter or setter message.
in the custom UITableViewHeaderFooterCell, the width of the reuse view can not be configed in a right way. And there is a warnning 'Setting the background color on UITableViewHeaderFooterView has been deprecated. Please use contentView.backgroundColor instead.' during the running.
the reason that the view that is added to xib is UITableViewCell. instead of UICollectionReusableView, the problems are fixed.
在定制UITableView的section的Footer时,重用的模板view不能正确的布局,width总不能正确匹配并且 程序运行时,总是出现'Setting the background color on UITableViewHeaderFooterView has been deprecated. Please use contentView.backgroundColor instead.'的警告。
原因是,在向xib添加view时,使用的是UITableViewCell,用UICollectionReusableView替换即可可解决问题。
@property (nonatomic, retain) IBOutlet Class * object;
@synthesize object;
- (IBAction) functionName:(id)sender;
- (IBAction) funtionName:(id) sender { }
Closing the keyboard
Value Changed
UIActionSheet a = [[UIActionSheet alloc] initWithTitle:@"title" delegate:self cancelButtonTitle:@"Cancel" destructiveButtonTitle:@"OK" otherButtontitle:nil]; [a showInView:self.view]; [a release];
UIAlertView a = [[UIAlertView alloc] initWithTitle:@"t" message:@"m" delegate:nil cancelButtonTitle:@"Cancel" otherButtonTitles:nil];
- (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation) interfaceOrientation; - (BOOL) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation) interfaceOrientatio duration:(NSTimeInterval) duration;
//UIInterfaceOrientationProtrait //UIInterfaceOrientationProtraitUpsideDown //UIInterfaceOrientationLandcapeLeft //UIInterfaceOrientationLandcapeRight if (interfaceOrientation == UIInterfaceOrientationPortrait) { button.frame = CGRectMake(0,0,100,100); }
self.view = self.portrait;
subview size by Interface Builder:Attributes - Simulated User Interface Elements
[self.oldViewController viewWillDisappear:YES]; [self.newViewController viewWillAppear:YES]; [self.oldViewController.view removeFromSuperView]; [self.view insertSubview:self.newViewController.view atIndex:0]; [self.oldViewController viewDidDisappear:YES]; [self.newViewController viewDidAppear:YES];
[UIView beginAnimations:@"view flip" context:nil]; [UIView setAnimationDuration:1.25]; [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut]; //UIViewAnimationTransitionFlipFromRight //UIViewAnimationTransitionFlipFromLeft //UIViewAnimationTransitionFlipCurlUp //UIViewAnimationTransitionFlipCurlDown [UIView setAnimationTransition:UIViewAnimationTransitionFlipFromRight forView:self.view cache:YES];
//set NSDate * now = [[NSDate alloc] init]; [datePicker setDate: now animated:NO]; [now release]; //get NSDate d = [datePicker date];
- (NSInteger) numberOfComponentsInPickerView:(UIPickerView * )pickerView { return column_number; } - (NSInteger)pickerView:(UIPickerView * )pickerView numberOfRowsInComponent:(NSInteger) component { return row_count; } - (NSString * )pickerView:(UIPickerView * )pickerView titleForRow:(NSInteger) row forComponent:(NSInteger) component { return row_component_string; } - (CGFloat)pickerView:(UIPickerView * )pickerView withForComponent:(NSInteger) component { return the_width_of_the_component; }
- (UIView * )pickerView:(UIPickerView * )pickerView viewForRow:(NSInteger) row forComponent:(NSInteger)component reusingView:(UIView * ) view { }
[picker selectRow:newValue inComponent:i animated:YES]; [picker reloadComponent:i];
import AudioToolbox.framework - Reference Type:Relative to Current SDK
NSString * path = [[NSBundle mainBundle]pathForResource:@"crunch" ofType:@"wav"]; SystemSoundID s; AudioServicesCreateSystemSoundID((CFURLRef)[NSURL fileURLWithPath:path], &s); AudioServicesPlaySystemSound(s);
[self performSelector:@selector(function-name) withObject:nil afterDelay:.5];
NSBundle * b = [NSBudle mainBundle]; NSString * p = [b pathForResource:@"name", ofType:@"suffix"];
- (NSInteger) tableView:(UITableView * )tableView numberOfRowsInSection:(NSInteger)section { return count_of_rows_in_section; } - (UITableViewCell * )tableView:(UITableView * )tableView cellForRowAtIndexPath:(NSIndexPath * )indexPath { static NSString tableId = @""; UITableViewCell * c = [tableView dequeueReusableCellWithIdentifier:tableId]; if (c == nil) { //UITableViewCellStyleSubtitle //UITableViewCellStyleValue1 //UITableViewCellStyleValue2 c = [[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:tableId] autorelease]; } c.imageView.image = [UIImage imageNamed:@"name.png"]; c.textLabel.text = [String stringWithFormat:@"%d", [indexPath row]]; c.detailTextLabel.text = @"detail"; return c; } - (NSInteger) tableView:(UITableView * )table indentationLevelForRowAtIndexPath:(NSIndexPath * )indexPath { return indentation_level; } - (NSIndexPath * ) tableView:(UITableView * )table willSelectRowAtIndexPath:(NSIndexPath * )indexPath { return indexPath; } - (void) tableView:(UITableView * )table didSelectRowAtIndexPath:(NSIndexPath * )indexPath { [tableView deselectRowAtIndexPath:indexPath animated:YES]; } - (CGFloat) tableView:(UITableView * )tableView heightForRowAtIndexPath:(NSIndexPath * )indexPath { return height; }
- (UITableViewCell * )tableView:(UITableView * )tableView cellForRowAtIndexPath:(NSIndexPath * )indexPath { static NSString tableId = @""; UITableViewCell * c = [tableView dequeueReusableCellWithIdentifier:tableId]; if (c == nil) { c = [[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:tableId] autorelease]; } CGRect rc = CGRectMake(0, 16, 70, 15); UILabel * l = [[UILabel alloc] initWithFrame:rc]; [c.contentView addSubview:l]; return c;
- (UITableViewCell * )tableView:(UITableView * )tableView cellForRowAtIndexPath:(NSIndexPath * )indexPath { static NSString tableId = @""; CustomCell * c = (CustomCell * )[tableView dequeueReusableCellWithIdentifier:tableId]; if (c == nil) { NSArray * nib = [[NBundle mainBundle] loadNibNamed:@"CustomCell" owner self options:nil]; for (id obj in nib) { if ([obj isKindOfClass:[CustomCell class]]) { c = (CustomCell * )obj; } } } return c; }
- (NSInteger) numberOfSectionsInTableView:(UITableView * )tableView { return count_of_section; } - (NSString * )tableView:(UITableView * )table titleForHeaderInSection:(NSInteger)section { return [NSString stringWithFormat(@"%@", section)]; }
- (NSArray * )sectionIndexTitlesForTableView:(UITableView * )tableView { return ; }
[window addSubview:nav];
Root View Controller identify is firstCtrller
firstCtrller.title = @"title"
[nav pushViewController:subController animated:YES];
[nav popViewControllerAnimated:YES];
//UITableVieCellAccessoryDisclosureIndicator //UITableVieCellAccessoryDisclosureButton //UITableViewCellAccessoryCheckmark //UITableViewCellAccessoryNone accessoryType = UITableViewCellAccessoryDisclosureIndicator;
- (void) tableView:(UITableView * )tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath * )indexPath { }
UIButton * btn = [UIButton buttonWIthType:UIButtonTypeCustom]; btn addTarget:self action:@selector(function_name:) forControlEvents:UIControlEventTouchUpInside]; cell.accessoryView = btn;
[self.tableView setEditing:!self.tableView.editing animated:YES];
UIBarButtonItem * b = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStyleBordered target:self action:@selector(fun)]; self.navigationItem.rightBarButton Item = b [b release];
- (UITableViewCell * )tableView:(UITableView * )tableView cellForRowAtIndexPath:(NSIndexPath * )indexPath { cell.showsRecorderControl = YES; } - (UITableViewCellEditingStyle)tableView:(UITableView * )tableView editingStyleForRowAtIndexPath:(NSIndexPath * )indexPath { return UITableViewCellEditingStyleNone; } - (BOOL)tableView:(UITableView * )tableView canMoveRowAtIndexPath:(NSIndexPath * )indexPath { return YES; } - (void)tableView:(UITableView * )tableView moveRowAtIndexPath:(NSIndexPath * )fromIndexPath toIndexPath:(NSIndexPath * )toIndexPath { } - (void)tableView:(UITableView * )tableView commitEditingStyle:(UITableViewCellEditingStyle) editingStyle forRowAtIndexPath:(NSIndexPath * )indexPath { [tableView deleteRowsAtInexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade]; }
[self.tableView reloadData];
Resource - Settings Bundle: Settings.bundle - Root.plist
Root Dictionary PreferenceSpecifiers Array Item 1 Dictionary Type PSGroupSpecifier Tile General Info Item 2 Dictionary Type String PSTextFieldSpecifier Title String Username Key String username AutocapitalizationType String None AutocorrectionType String No Item 3 Dictionary Type String PSTextFieldSpecifier Title String Password Key String password AutocapitalizationType String None AutocorrectionType String No IsSecure Boolean Yes Item 4 Dictionary Type String PSMultiValueSpecifier Title String Protocol Key String protocol DefaultValue String SMTP Titles Array Item 1 String HTTP Item 2 String SMTP Item 3 String NNTP Item 4 String IMAP Item 5 String POP3 Values Array Item 1 String HTTP Item 2 String SMTP Item 3 String NNTP Item 4 String IMAP Item 5 String POP3 Item 5 Dictionary Type String PSToggleSwitchpecifier Title String WarpDriver Key String warp TrueValue String Engaged FalseValue String Disabled DefaultValue String Engaged Item 6 Dictionary Type PSGroupSpecifier Tile Warp Factor Item 7 Dictionary Type String PSSliderSpecifier Key String warpfactor DefaultValue String 5 MinimumValue String 1 MaximumValue String 10 MinimumValueImage String min.png MaximumValueImage String max.png Item 8 Dictionary Type PSGroupSpecifier Tile Additional Info Item 9 Dictionary Type String PSSchildPaneSpecifier Tile String More Settings File String More
NSUserDefaults d = [NSUserDefaults standardUserDefaults]; [d setObject:@"value" forKey:@"key"]; [d objectForKey:@"key"];
usr tmp Root Media Libary Preferences -- NSUserDefaults Applications Documents Library tmp
NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDoumentDirectory, NSUserDomainMask, YES); NSString * directory = paths[0] NSString * file = [directory stringByAppendingPathComponent:@"filename"];
NSString * tmp = NSTemporaryDirectory(); NSString * f = [tmp stringByAppendingComponent:@"filename"];
Array Dictionary Data String Number Date
//write [obj writeToFile:@"path":atomically:YES]; //read if ([NSFileManager defaultManager] fileExistsAtPath:filePath]) { obj = [[class alloc]initWithContentFile:filePath]; }
- (void) encodeWithCoder:(NSCoder * )encoder { [super encodeWithCoder:encode]; [encode encodeObject: self.obj forKey: @"key"]; } - (id) initWithCode: (NSCoder * )decoder { if (self = [super init]) { self.obj = [decoder decodeObjectForKey:@"key"]; } return self; } - (id) copyWithZone:(NSZone * ) zone { Class * copy = [[self class] allocWithZone:zone] init]; copy.obj = [[self.obj copyWithZone:zone] autorelease]; return copy; }
NSMutableData * data = [[NSMutableData alloc] init]; NSKeyedArchiver * archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data]; [archiver encodeObject:obj forKey:@"root"]; [archiver finishEncoding]; [data finishEncoding]; [data writeToFile: [self dataFilePath] atomically:YES]; [obj release]; [archiver release]; [data release];
NSData * data = [[NSMutableData alloc] initWithContentsOfFile: [self path]]; NSKeyedUnarchiver * unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData: data]; Class * obj = [unarchiver decodeObjectForKey:@"root"]; [unarchiver finishDecoding]; //do something ... [unarchiver release]; [data release];
sqlite3 * db; sqlite3_open([path UTF8String]); char* err; sqlite3_exec(db, sql, NUL, NULL, &err); sqlite3_stmt * statement; char * sql = "select id, value from tb"; sqlite3_prepare_v2(db, sql, -1, &statement, 0); while (sqlite3_step(statement) == SQLITE_ROM) { int id = sqlite3_column_int(statement, 0); char* d = (char*)sqlite3_column_text(statement, 1); NSString value = [[NSString alloc] initWithUTF8String:d]; //do something... [value release]; } char * sql = "insert into tb values (?, ?);"; sqlite3_stmt * stmt; if (sqlite3_prepare_v2(database, sql, -1, &stmt, nil) == SQLITE_OK) { sqlite3_bind_int(stmt, 1, 235); sqlite3_bind_text(stmt, 2, "value", -1, NULL); } if (sqlite3_step(stmt) != SQLITE_DONE) { //error to do something ... } sqlite3_finalize(stmt); sqlite3_close(db);
NSManagedObjectContext ctx = [[[UIApplication sharedApplication] delegate] managedObjectContext];
NSManagedObject * t = [NSEntityDescription insertNewObjectForEntityForName:@"s" inManagedObjectContext:ctx];
NSFetchRequest * r = [[NSFetchRequest alloc] init]; NSEntityDescription * ed= [NSEntityDescription entityForName:@"s" inManagedObjectContext:ctx]; [r setEntity:ed]; [ctx save:&e];
NSPredicate * pred = [NSPredicate predicateWithFormat:@"(s = %@)", s]; [r setPredicate: pred]; NSError * e; NSArray * objs = [ctx executeFetchRequest:r error: &e]; if (objs == nil) { //error... }
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillTerminate:) name:UIApplicationWillTerminateNotification object:app];
The Quartz 2D API is part of the Core Graphics framework, so you may see Quartz referred to as Core Graphics or, simply, CG.
struct CGPoint { float x; float y; }; struct CGSize { float width; float height; }; struct CGRect { CGPoint origin; CGSize size; };
UIColor c = [UIColor colorWithRed:1.0f green:0.0f blue:0.0f alpha:1.0f]; c.CGColor;
[self setNeedsDisplay]; - (void)drawRect:(CGRect)rect { CGContextRef ctx = UIGraphicsGetCurrentContext(); CGContextSetLineWidth(ctx, 2.0); CGContextSetStrokeColorWithColor(ctx, clr.CGColor); //draw line CGContextMoveToPoint(ctx, p1.x, p1.y); CGContextAddLineToPoint(ctx, p2.x, p2.x); CGContextStrokePath(ctx); CGContextSetFillColorWithColor(ctx, clr.CGColor); CGRect rc = CGRectMake(x, y, w, h); //draw rect CGContextAddRect(ctx, rc); CGContextDrawPath(ctx, kCGPathFillStroke); //draw ellipse CGContextAddEllipseInRect(ctx, rc); CGContextDrawPath(ctx, kCGPathFillStroke); //draw image [[UIImage imagedNamed:@"image.png"]drawAtPoint:p]; }
CGRect dirty_rc = CRectUnion(old_rc, current_rc) [self setNeedsDisplayInRect:dirty_rc];
//reset virtual world glLoadIdentity(); //clean background glClearColor(r, g, b, a); glClear(GL_COLOR_BUFFER_BIT); //set color CGFloat c = CGColorGetComponents((CGColorRef)color.GCColor); CGFloat * r = c[0]; CGFloat * g = c[1]; CGFloat * b = c[2]; glColor4f(r, g, b, 1.0); //disable texture gDisable(GL_TEXTURE_2D); //convert to vertex point and draw vertex points GLfloat vec[4]; vec[0] = p1.x; vec[1] = self.frame.size.height - p1.y; vec[2] = p2.x; vec[3] = self.frame.size.height - p2.y; gLineWidth(2.0); glVertexPointer(2, GL_FLOAT, 0, vec); glDrawArray(GL_LINES, 0, 2); //render glBindRenderbufferOES(GL_RENDERBUFFER_OES, viewRenderbuffer); [context presentRenderbuffer:GL_RENDERBUFFER_OES]; //draw image s = [[Texture2D alloc] initWithImage:[UIImage imaged:@"picture.png"]]; glBindTexture(GL_TEXTURE_2D, s.name); glEnable(GL_TEXTURE_2D); [s drawAtPoint:CGPointMake(x, self.fram.size.height - y)];
- (void) touchesBegan:(NSSet * )touches withEvent:(UIEvent * ) event { [event touchesForView:self.view]; UITouch t = [touches andObject]; [t tapCount]; CGPoint p = [t locationInView:self]; } - (void) touchesCancelled:(NSSet * )touches withEvent:(UIEvent * ) event { } - (void) touchesEnded:(NSSet * )touches withEvent:(UIEvent * ) event { } - (void) touchesMoved:(NSSet * )touches withEvent:(UIEvent * ) event { }
three technologies: * GPS * cell ID location * Wi-Fi
self.lmgr = [[CLLocationManger alloc] init]; locationManager.delegate = self; //kCLLocationAccuracyNearestTenMeters //kCLLocationAccuracyNearestHundredMeters //kCLLocationAccuracyNearestKilometers //kCLLocationAccuracyNearestThreeKilometers locationManager.desiredAccuracy = kCLLocationAccuracyBest; //float locationManager.distanceFilter = kCLDistanceFilterNone; [locationMnager startUpdatingLocation];
CLLocationDegrees latitude = l.coordinate.latitude; CLLocationDegrees longitude = l.coordinate.longitude; CLLocationDistance altitude = l.altitude; CLLocationAccuracy hAccuracy = l.horizontalAccuracy CLLocationAccuracy vAccuracy = l.verticalAccuracy CLLocationDistance distance = [from getDistanceFrom:to]; CLLocationDistance distance = [from getDistanceFrom:to];
@interface where:UIViewController{ CLLocationManager * lmgr; } @end @implementation where - (void) locationManager:(CLLocationManager * )manager didUpdateToLocation:(CLLocation * )newLocation fromLocation:(CLLocation * ) oldLocation { } - (void) locationManager:(CLLocationManager * )manager didFailWithError:(NSError * )error { error.code; } @end
Info.plist UIStatusBarHidden Boolean
UIAccelerometer * a = [UIAccelermeter sharedAccelerometer]; a.delegate = self; a.updateInterval = 1.0f/6.0f;
@interface VCer:UIViewController{ }
- (void) accelerometer:(UIAccelerometer * ) accelerometer didAccelerate:(UIAcceleration * ) acceleration { //acceleration.x; //acceleration.y; //acceleration.z; }if ([UIIMagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypePhotoLibrary]) { UIImagePickerController * picker = [[UIImagePickerController alloc] init]; picker.delegate = self; //UIImagePickerControllerSourceTypeCamera //UIImagePickerControllerSourceTypeSavedPhotosAlbum picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary; [self presentModalViewController:picker animated:YES]; [picker release]; }@interface VCer:NSObject < UIIMagePickerControllerDelegate, UINavigationControllerDelegate > { }- (void)imagePickerController:(UIImagePickerController * )picker didFinishPickingImage:(UIImage * )image editingInfo:(NSDictionary * )editingInfo { UIImage * selectedImage = image; UIImage * originalImage = [editingInfo objectForKey: UIImagePickerControllerOriginalImage]; // NSValue * cropRect = [editingInfo objectForKey:UIIMagePickerControllerCropRect]; CGRect theRect = [cropRect CGRectValue]; //TODO: [picker dismissModalViewControllerAnimated:YES]; } - (void)imagePickerControllerDidCancel { [picker dismissModalViewControllerAnimated:YES]; }Chapter 17 Localization
Localiztion project (.lproj)
The Localized String Macro(NSLocalizedString)
NSLocale * locale = [NSLocale currentLocale]; NSString * displayNameString = [locale displayNameForKey:NSLocaleIdentifier value:[locale localeIdentifier]];Localizing xib
generating and localizing a string file
genstring paths/all m files日期: 2015-09-28 17:30:06, 9 years and 110 days ago