atomic只能保证读写的原子性,即有三个线程A,B,C 同时操作一个atomic的属性p。其中 线程A读取p值,线程B和线程C分别向p赋值。在这种情况下线程A读取的p值只可能有三种情 况,A初始值,线程B赋的值和线程C赋的值。因为,atomic保证了读写操作的原子性。但线 程A所读的值是不能确定的,所以不具备线程安全性。另外,如果出现线程D,在线程A,B, C进行读写操作的同时,释放掉属性p,则有几率会造成崩溃,也是线程不安全的情况。

标签: objc
日期: 2016-11-18 17:30:06, 8 years and 58 days ago

Objective-C 调用 Swift

Swift 类

Swift类定义前加入@objc关键字,并使类继承自NSObject

@objc class S : NSObject{
    func m() {
        print(__FUNCTION__)
    }
}

在调用Swift代码的Objc文件中加入名类似为"xxx-Swift.h"的头文件

头文件具体的名字可在 设置选项:

{project} - {targets} - {build settings} - {swift compiler - code generation} - {Objective-C Generated Interface Header Name}

objc调用swift头文件名


 #import "objc_swift-Swift.h"
int main(int argc, const char * argv[]) {
   @autoreleasepool {
        S* s = [[S alloc]init];
        [s m];
    }
    return 0;
 }

Swift 调用 Objective-C

创建桥接文件

创建桥接文件

选择Create Bridging Header

桥接文件在如下设置位置

{project} - {targets} - {build settings} - {swift compiler - code generation} - {Objective-C Bridging Header}

将要调用的ObjC类头文件import至桥接文件中

//
//  Use this file to import your target's public headers that you would like to expose to Swift.
//

 #import "O.h"

ObjC 代码

.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__)
    }
}

示例工程

objc-swift

标签: objc, swift, cocoa, xos
日期: 2016-04-01 17:30:06, 8 years and 289 days ago
  • 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.

标签: objc, cocoa
日期: 2016-02-26 17:30:06, 8 years and 324 days ago

解决UITableVIewHeaderCell的布局和警告问题

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替换即可可解决问题。

标签: ios, objc, cocoa
日期: 2015-10-23 17:30:06, 9 years and 85 days ago

Chapter 1 and 2 Welcome

  • The first app:hello, iOS!
  • Xcode
    • groups & Files
  • Interface Builder
    • xib window
    • File's Owner
    • add a object and connect it to source code object
    • view window
    • library window
    • inspector
    • attributes
    • connection
    • size
    • identify
  • icon $_Info.plist -> Icon File

Chapter 3 Handling Basic Intraction

Xcode project templates

MVC pattern

IBOutlet

@property (nonatomic, retain) IBOutlet Class * object;
@synthesize object;

IBAction

- (IBAction) functionName:(id)sender;
- (IBAction) funtionName:(id) sender {
}

UIApplicationDelegate

ViewController

Chapter 4 More User Interface Fun

UIImageView

UILabel

UITextField

  • Return or Done
    • Return:change the another view
    • Done:back to the current view
  • Closing the keyboard

    • UITextField, Did End On Exit
    • UIControl, Touch Down
    • resignFirstResponder
  • Value Changed

UISwitch

UISegmentedControl

  • Value Changed

UIButton

  • Touch Up Inside

comment

  • //TODO:

Action Sheet

implement action sheet

UIActionSheet a = [[UIActionSheet alloc] initWithTitle:@"title" delegate:self cancelButtonTitle:@"Cancel" destructiveButtonTitle:@"OK" otherButtontitle:nil];
[a showInView:self.view];
[a release];

UIActionSheetDelegate, didDismissWithButtonIndex

Alert

implement alert

UIAlertView a = [[UIAlertView alloc] initWithTitle:@"t" message:@"m" delegate:nil cancelButtonTitle:@"Cancel" otherButtonTitles:nil];

UIAlertViewDelegate

Chapter 5 rotation and resize

iPhone4(iPhone3, iPhone3 GS) pixel: 320x480

- (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);
}

portrait and landscape views

self.view = self.portrait;

Chapter 6 Multiview

subview size by Interface Builder:Attributes - Simulated User Interface Elements

switch view

[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];

view animation

[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];

Chapter 7 Tab bars and Pickers

Tab bars

  • View Controllers
  • icon 24x24 pixel
  • Tab Bar Item

Picker

Date Picker

//set
NSDate * now = [[NSDate alloc] init];
[datePicker setDate: now animated:NO];
[now release];
//get
NSDate d = [datePicker date];

Picker

- (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;
}

Custom Picker

- (UIView * )pickerView:(UIPickerView * )pickerView viewForRow:(NSInteger) row forComponent:(NSInteger)component reusingView:(UIView * ) view {
}

UIPickerView rolls and selects row

[picker selectRow:newValue inComponent:i animated:YES];
[picker reloadComponent:i];

Audio

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);

delay to perform

[self performSelector:@selector(function-name) withObject:nil afterDelay:.5];

pragma



bundle

NSBundle * b = [NSBudle mainBundle];
NSString * p = [b pathForResource:@"name", ofType:@"suffix"];

Chapter 8 Table Views

Grouped and Plain tables

data source and delegate

- (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;
}

Custom

child view

- (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;

inherit UITableViewCell

- (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;
}

Section

- (NSInteger) numberOfSectionsInTableView:(UITableView * )tableView {
    return count_of_section;
}
- (NSString * )tableView:(UITableView * )table titleForHeaderInSection:(NSInteger)section {
    return [NSString stringWithFormat(@"%@", section)];
}

Indexed

- (NSArray * )sectionIndexTitlesForTableView:(UITableView * )tableView {
    return ;
}

search

  • earch bar
    • searchBarTextDidBeginEditing:
    • searchBar:textDidChange
    • searchBarCancelButtonClicked

Chapter 9 Navigation Controllers and Table Views

Navigation

1. add nav(UINavigationController) in window(NSWindow)

[window addSubview:nav];

2. set firstView(UITableViewController) as nav rootViewController

Root View Controller identify is firstCtrller

3. title

firstCtrller.title = @"title"

4. navigate a view

[nav pushViewController:subController animated:YES];

5. back to view

[nav popViewControllerAnimated:YES];

Table view

accessory

//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;

edit mode

[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];

Chapter 10 Setting and Defaults

Setting

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

Defaults

NSUserDefaults d = [NSUserDefaults standardUserDefaults];
[d setObject:@"value" forKey:@"key"];
[d objectForKey:@"key"];

Chapter 11 Data Persistence

File

usr
    tmp
    Root
    Media
    Libary
        Preferences -- NSUserDefaults
    Applications
        Documents
        Library
        tmp

Applications/Documents

NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDoumentDirectory, NSUserDomainMask, YES);
NSString * directory = paths[0]
NSString * file = [directory stringByAppendingPathComponent:@"filename"];

Applications/tmp

NSString * tmp = NSTemporaryDirectory();
NSString * f = [tmp stringByAppendingComponent:@"filename"];

Property List

Array Dictionary Data String Number Date

//write
[obj writeToFile:@"path":atomically:YES];
//read
if ([NSFileManager defaultManager] fileExistsAtPath:filePath]) {
    obj = [[class alloc]initWithContentFile:filePath];
}

Archives

protocol

- (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;
}

write

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];

read

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

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);

Core Data

use core data storage

CoreData.xcdatamodel

Entity

Managed Object

Attribute

Relationship

Fetched property

persistent store (backing store)

  • SQLite3, XML, memory store can be implemented for backing store
  • backing store is created and configured in BIDAppDelegate
NSManagedObjectContext ctx = [[[UIApplication sharedApplication] delegate] managedObjectContext];

Create

NSManagedObject * t = [NSEntityDescription insertNewObjectForEntityForName:@"s" inManagedObjectContext:ctx];

Retrieve

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...
}

observer pattern

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillTerminate:) name:UIApplicationWillTerminateNotification object:app];

Chapter 12 Quartz and OpenGL

Quartz 2D

The Quartz 2D API is part of the Core Graphics framework, so you may see Quartz referred to as Core Graphics or, simply, CG.

coordinate

CGPoint CGSize CGRect

struct CGPoint {
    float x;
    float y;
};
struct CGSize {
    float width;
    float height;
};
struct CGRect {
    CGPoint origin;
    CGSize size;
};

UIColor

Mode:RGBA HSV HSL CMYK

Create and CGColor

UIColor c = [UIColor colorWithRed:1.0f green:0.0f blue:0.0f alpha:1.0f];
c.CGColor;

Draw

[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];
}

Optimizing

CGRect dirty_rc = CRectUnion(old_rc, current_rc)
[self setNeedsDisplayInRect:dirty_rc];

OpenGL ES

OpenGL ES = OpenGL Embeded System

OpenGL 3D coordinate to View 2D coordinate

Texture2D creates opengl 2d textures from images or text

draw

//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)];

Chapter 13 Taps, Touches and Gestures

responder chain

touches:the starting phase of the event

event:representing the event.

- (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 {
}

Chapter 14 Core Location

three technologies: * GPS * cell ID location * Wi-Fi

start

self.lmgr = [[CLLocationManger alloc] init];
locationManager.delegate = self;
//kCLLocationAccuracyNearestTenMeters
//kCLLocationAccuracyNearestHundredMeters
//kCLLocationAccuracyNearestKilometers
//kCLLocationAccuracyNearestThreeKilometers
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
//float
locationManager.distanceFilter = kCLDistanceFilterNone;
[locationMnager startUpdatingLocation];

CLLocation

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];

delegate

@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

Chapter 15 Accelerometer

Hide status Bar

Info.plist UIStatusBarHidden Boolean

Accelerometer

  • portrait:y = -1.0
  • upside down:y = 1.0
  • landscape left:x = 1.0
  • landscape right:x= -1.0
  • laying with back:z = -1.0
  • laying with front:z = 1.0
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
标签: ios, objc
日期: 2015-09-28 17:30:06, 9 years and 110 days ago