* 특정 포맷의 문자열 작성
NSString *aString = @"Cool";
NSString *myString = [NSString stringWithFormat:@"It's '%@'", aString];
* 문자열 수정
- (NSString *)stringByAppendingString:(NSString *)string;
- (NSString *)stringByAppendingFormat:(NSString *)string;
- (NSString *)stringByDeletingPathComponent;
NSString *myString = @"Hello";
NSString *fullString;
fullString = [myString stringByAppendingString:@" world!"]; // Hello world!
* 유용 NSString methods
- (BOOL)isEqualToString:(NSString *)string;
- (BOOL)hasPrefix:(NSString *)string;
- (int)intValue;
- (double)doubleValue;
* 유용 NSMutableString methods
+ (id)string;
- (void)appendString:(NSString *)string;
- (void)appendFormat:(NSString *)format, ...;
* 유용 NSArray methods
+ arrayWithObjects:(id)firstObj, ...;
- (unsigned)count;
- (id)objectAtIndex:(unsigned)index;
- (unsigned)indexOfObject:(id)object;
* 유용 NSMutableArray methods
+ (NSMutableArray *)array;
- (void)addObject:(id)object;
- (void)removeObject:(id)oject;
- (void)removeAllObjects;
- (void)insertObject:(id)object atIndex:(unsigned)index;
* 유용 NSDictionary methods
+ dictionaryWithObjectsAndKeys:(id)firstObject, ...;
- (unsigned)count;
- (id)objectForKey:(id)key;
* 유용 NSMutableDictionary methods
+ (NSMutableDictionary *)dictionary;
- (void)setObject:(id)object forKey:(id)key;
- (void)removeObjectForKey:(id)key;
- (void)removeAllObjects;
[colors setObject:@"Orange" forKey:@"HighlightColor"];
* 유용 NSSet methods : Unordered collection of objects
+ setWithObjects:(id)firstObj, ...;
- (unsigned)count;
- (BOOL)containsObject:(id)object;
* 유용 NSMutableSet methods
+ (NSMutableSet *)set;
- (void)addObject:(id)object;
- (void)removeObject:(id)object;
- (void)removeAllObjects;
- (void)intersectSet:(NSSet *)otherSet;
- (void)minusSet:(NSSet *)otherSet;
* 유용 NSNumber methods
+ (NSNumber *)numberWithInt:(int)value;
+ (NSNumber *)numberWithDouble:(double)value;
- (int)intValue;
- (double)doubleValue;
* Selectors 활용 예
SEL mySelector = @selector(name);
SEL anotherSelector = @selector(setName:);
SEL lastSelector = @selector(doStuff:withThing:andThing:); // 3개의 arguments
* 클래스 / 인스턴스 메소드
+ methodName : 클래스 메소드
- methodName : 인스턴스 메소드
* 아이폰 시뮬레이터 단축키
스크린 방향 바꾸기 : command+왼쪽 화살표, command+오른쪽 화살표
홈으로 돌아가기 : command+shift+H
폰 잠그기 : command+L
* 자동회전과 리사이즈에 대한 지원
contentView.autoresizesSubviews = YES;
contentView.autoresizingMask = (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
* 하위뷰 추가
[parentView addSubview:child];
* 하위뷰 확인
[parentView subviews];
* 하위뷰 제거
[childView removeFromSuperview];
* 하위뷰 순서 변경
[parentView exchangeSubviewAtIndex:i withSubviewAtIndex:j];
* 직사각형 정의
CGRectMake(origin.x, origin.y, size.with, size.height);
* CGRect 구조체를 문자열로 변환
NSStringFromCGRect(myCGRect);
* 문자열을 CGRect 구조체로 변환
CGRectFromString(myString);
* 동일 위치에 정렬된 직사각형 생성
CGRectInset(myCGRect);
* 구조체 교차여부 확인
CGRectIntersectsRect(rect1, rect2);
* (0,0)에 위치한 높이 0의 직사각형 상수
CGRectZero;
* 상태바 숨기기
[[UIApplication sharedApplication] setStatusBarHidden:YES animated:YES];
* 가로보기 모드로 강제 전환
[[UIApplication sharedApplication] setStatusBarOrientation:UIInterfaceOrientationLandscapeRight];
* 랜덤함수 사용예(3개의 색깔중 하나 선택)
NSString *myColor = [[NSArray arrayWithObjects:@"blue", @"red", @"green", nil] objectAtIndex:(random() % 3)];
* 드래그 뷰 생성
DragView *dragger = [[DragView alloc] initWithFrame:dragRect];
* 사용자 상호작용 설정
[dragger setUserInteractionEnabled:YES];
* 선택한 뷰를 맨 앞으로 가져옴
[[self superview] bringSubviewToFront:self];
* 사용자 디폴트 저장하기
[[NSUserDefaults standardUserDefaults] setObject:myScore forKey:@"myScore"];
[[NSUserDefaults standardUserDefaults] synchronize];
* 사용자 디폴트 불러오기
NSMutableArray *myScore;
myScore = [[NSUserDefaults standardUserDefaults] objectForKey:@"myScore"];
* 상단 버튼 삽입(setPlus는 함수명)
self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithTitle:@"더하기" style:UIBarButtonItemStylePlain target:self action:@selector(setPlus)] autorelease];
* Superclass methods
Implicit variable, "self" : Like "this" in Java and C++
Superclass methods, "super"
* Object Creation
1st step : allocate memory to store the object
2nd step : initialize object state
+ alloc : class method(cf. dealloc for destruction)
- init : instance method
Person *person = nil;
person = [[Person alloc] init];
* Multiple init methods
- (id)init;
- (id)initWithName:(NSString *)name;
- (id)initWithName:(NSString *)name age:(int)age;
- (id) init {
return [self initWithName:@"No Name"];
}
- (id) initWithName:(NSString *)name {
return [self initWithName:name age:0];
}
* Reference Counting
As long as retain count is greater than zero, object is alive and valid.
+alloc and -copy create objects with retain count == 1.
-retain increments retain count.
-release decrements retain count.
When retain count reaches 0, object is destroyed.(-dealloc method invoked automatically.)
You only deal with alloc, copy, retain, release.
You never call dealloc explicitly in your code except for "[super dealloc]".
* Returning a newly created object
- (NSString *) fullName {
NSString *result;
result = [[NSString alloc] initWithFormat:@"%@ %@", firstName, lastName];
[result autorelease];
return result;
}
The result is released, but not right away. Caller gets valid object and could retain if needed.
* Getters and Setters
- (int)age;
- (void)setAge:(int)age;
* Properties allow access to setters and getters through dot syntax
@property age;
int theAge = person.age;
person.age = 21;
* Various methods of UIApplicationDelegate
- (void)applicationDidFinishLaunching:(UIApplication *)application;
- (void)applicationWillTerminate:(UIApplication *)application;
- (void)applicationWillResignActive:(UIApplication *)application;
- (void)application:(UIApplication *)application handleOpenURL:(NSURL *)url;
- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application;
* 3 different flavors of action method selector types
- (void)actionMethod;
- (void)actionMethod:(id)sender;
- (void)actionMethod:(id)sender withEvent:(UIEvent *)event;
* Manual Target-Action
@interface UIControl;
- (void)addTarget:(id)target action:(SEL)action forControlEvents:(UIControlEvents)controlEvents;
- (void)removeTarget:(id)target action:(SEL)action forControlEvents:(UIControlEvents)controlEvents;
@end
> Stanford Lecture #5
* Add/remove views
- (void)addSubview:(UIView *)view;
- (void)removeFromSuperview;
* Manipulate the view hierarchy
- (void)insertSubview:(UIView *)view atIndex:(int)index;
- (void)insertSubview:(UIView *)view belowSubview:(UIView *)view;
- (void)insertSubview:(UIView *)view aboveSubview:(UIView *)view;
- (void)exchangeSubviewAtIndex:(int)index withSubviewAtIndex:(int)otherindex;
* 일시적으로 뷰 감추기
myView.hidden = YES;
* View location
CGPoint(x, y);
* View dimension
CGSize(width, height);
* View location and dimension
CGRect(origin, size);
* Manual view creation
CGRect frame = CGRectMake(20, 45, 140, 21);
UILabel *label = [[UILabel alloc] initWithFrame:frame];
[window addSubview:label];
[label setText:@"Number of sides:"];
[label release];
* Defining custom views
- (void)drawRect:(CGRect)rect;
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event;
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event;
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event;
* When a view needs to be redrawn, use:
- (void)setNeedsDisplay;
[polygonView setNeedsDisplay];
* Access the graphics context within drawRect: by calling
(CGContextRef)UIGraphicsGetCurrentContext(void);
* 색상 설정
UIColor *redColor = [UIColor redColor];
[redColor set];
// [[UIColor redColor] set] 과 동일
* 폰트 설정
UIFont *font = [UIFont systemFontOfSize:14.0];
[myLabel setFont:font];
* 도형 색 채우기
UIRectFill(square);
* 테두리 색 채우기
UIRectFrame(square);
* 이미지 삽입하는 3가지 방법
+ [UIImage imageNamed:(NSString *)name];
- [UIImage initWithContentsOfFile:(NSString *)path];
- [UIImage initWithData:(NSData *)data];
* Bitmap image example
UIGraphicsBeginImageContext(size);
// drawing code...
result = UIGraphicsGetImageFromCurrentContext();
UIGraphicsEndImageContext();
return result;
* Getting image data
NSData *UIImagePNGRepresentation (UIImage *image);
NSData *UIImageJPGRepresentation (UIImage *image);
* Drawing text & images
- [UIImage drawAtPoint:(CGPoint)point);
- [UIImage drawInRect:(CGRect)rect);
- [UIImage drawAsPatternInRect:(CGRect)rect);
- [NSString drawAtPoint:(CGPoint)point withFont:(UIFont *)font];
* View animation example
- (void)showAdvancedOptions {
[UIView beginAnimations:@"advancedAnimations" context:nil];
[UIView setAnimationDuration:0.3];
// make optionsView visible
optionsView.alpha = 1.0;
// move the polygonView down
CGRect polygonFrame = polygonView.frame;
polygonFrame.origin.y += 200;
polygonView.frame = polygonFrame;
[UIView commitAnimations];
}
* View transforms
CGAffineTransformScale(transform, xScale, yScale);
CGAffineTransformRotate(transform, angle);
CGAffineTransformTranslate(transform, xDelta, yDelta);
* Saving state across app launches
+ (NSUserDefaults *)standardUserDefaults;
- (int)integerForKey:(NSString *)key;
- (void)setInteger:(int)value forKey:(NSString *)key;
- (id)objectForKey:(NSString *)key;
- (void)setObject:(id)value forKey:(NSString *)key;
* Creating a view in Code
- (void)loadView{
MyView *myView = [[MyView alloc] initWithFrame:frame];
self.view = myView;
[myView release];
}
* View controller lifecycle
- (id)initWithNibName:(NSString *)nibName bundle:(NSBundle *)bundle { }
- (void)viewDidLoad {}
- (void)viewWillAppear:(BOOL)animated {}
- (void)viewWillDisappear:(BOOL)animated {}
* Loading & Saving data
NSUserDefaults
Property lists
SQLite
Web services
* Supporting interface rotation
- (void)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
return (interfaceOrientation == UIInterfaceOrientationPortrait);
// This view controller only supports portrait.
// retrun (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
// This view controller supports all orientations except for upside-down.
}
* Autoresizing your views
view.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
view.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin;
* Push to add a view controller
- (void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated;
* Pop to remove a view controller
- (void)popViewControllerAnimated:(BOOL)animated;
* Pushing your first view controller
- (void)applicationDidFinishLaunching:(UIApplication *)application {
navController = [[UINavigationController alloc] init];
[navController pushViewController:firstViewController animated:NO];
[window addSubview:navController.view];
}
* Push from within a view controller on the desk
- (void)myAction:(id)sender{
UIViewController *viewController = ...;
[self.navigationController pushViewController:viewController animated:YES];
}
* Text bar button item
- (void)viewDidLoad{
UIBarButtonItem *fooButton = [[UIBarButtonItem alloc] initWithTitle:@"Foo" style:UIBarButtonItemStyleBordered target:self action:@selector(foo:)];
self.navigationItem.leftBarButtonItem = fooButton;
[fooButton release];
}
* System bar button item
- (void)viewDidLoad{
UIBarButtonItem *addButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd style:UIBarButtonItemStyleBordered target:self action:@selector(add:)];
self.navigationItem.rightBarButtonItem = addButton;
[addButton release];
}
* Edit/Done button
self.navigationItem.leftBarButtonItem = self.editButtonItem;
- (void)setEditing:(BOOL)editing animated:(BOOL)animated{
// Update appearance of views
}
* Custom title view
UISegmentedControl *segmentedControl = ...;
self.navigationItem.titleView = segmentedControl;
[segmentedControl release];
* Back button
self.title = @"Hello there, CS193P!";
UIBarButtonItem *heyButton = [[UIBarButtonItem alloc] initWithTitle:@"Hey!" ...];
self.navigationItem.backButtonItem = heyButton;
[heyButton release];
vs.
* Setting up a Tab Bar controller
- (void)applicationDidFinishLaunching:(UIApplication *)application {
tabBarController = [[UITabBarController alloc] init];
tabBarController.viewControllers = myViewControllers;
[window addSubview:tabBarController.view];
}
* Creating Tab Bar items : Title and image
- (void)viewDidLoad{
self.tabBarItem = [[UITabBarItem alloc] initWithTitle:@"Playlists" image:[UIImage imageNamed:@"music.png"] tag:0];
}
* Creating Tab Bar items : System item
- (void)viewDidLoad{
self.tabBarItem = [[UITabBarItem alloc] initWithTabBarSystemItem:UITabBarSystemItemBookmarks tag:0];
}
* Nesting Navigation Controllers
- Create a Tab Bar controller
tabBarController = [[UITabBarController alloc] init];
- Create each Navigation controller
navController = [[UINavigationController alloc] init];
[navController pushViewController:firstViewController animated:NO];
- Add them to the Tab Bar controller
tabBarController.viewControllers = [NSArray arrayWithObjects:navController, anotherNavController, someViewController, nil];
* Using a Scroll View
// Create with the desired frame
CGRect frame = CGRectMake(0, 0, 200, 200);
// Add subviews
frame = CGRectMake(0, 0, 500, 500);
myImageView = [[UIImageView alloc] initWithFrame:frame];
[scrollView addSubview:myImageView];
// Set the content size
scrollView.contentSize = CGSizeMake(500, 500);
* UIScrollView delegate
@protocol UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView;
...
- (BOOL)scrollViewShouldScrollToTop:(UIScrollView *)scrollView;
@end
* Zooming with a Scroll View
scrollView.maximumZoomScale = 2.0;
scrollView.minimumZoomScale = scrollView.size.width / myImage.size.width;
- (UIView *)viewForZoomingInScrollView:(UIView *)view{
return someViewThatWillBeScaled;
}
* Provide number of sections and rows
- (NSInteger)numberOfSectionsInTableView:(UITableView *)table;
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section;
* Provide cells for table view as needed
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;
* Category on NSIndexPath with helper methods
+ (NSIndexPath *)indexPathForRow:(NSUInteger)row inSection:(NSUInteger)section;
@property(nonatomic,readonly) NSUInteger section;
@property(nonatomic,readonly) NSUInteger row;
@end
* Cell reuse
- (UITableViewCell *)dequeueReusableCellWithIdentifier:(NSString *)identifier;
* Triggering updates
- (void)viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];
[self.tableView reloadData];
}
* Customize appearance of table view cell
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath;
* Validate and respond to selection changes
- (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath;
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath;
* Responding to selection
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
NSUInteger row = indexPath.row;
id objectToDisplay = [myObjects objectAtIndex:row];
MyViewController *myViewController = ...;
myViewController.object = objectToDisplay;
[self.navigationController pushViewController:myViewController animated:YES];
}
* Altering or disabling selection
- (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath{
if(indexPath.row == ...){
return nil;
}else{
return indexPath;
}
}
* Accessory types
- (UITableViewCellAccessoryType)tableView:(UITableView *)table accessoryTypeForRowWithIndexPath:(NSIndexPath *)indexPath;
UITableViewCellAccessoryDisclosureIndicator
UITableViewCellAccessoryDetailDisclosureButton
UITableViewCellAccessoryCheckmark
- (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath{
NSUInteger row = indexPath.row;
...
}
* Add additional views to the content view
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell *cell = ...;
CGRect frame = cell.contentView.bounds;
UILabel *myLabel = [[UILabel alloc] initWithFrame:frame];
myLabel.text = ...;
[cell.contentView addSubview:myLabel];
[myLabel release];
}
* Custom row heights
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
NSString *text = ...;
UIFont *font = [UIFont systemFontOfSize:...];
CGSize withinSize = CGSizeMake(tableView.width, 1000];
CGSize size = [text sizeWithFont:font constrainedToSize:withinSize lineBreakMode:UILineBreakModeWordWrap];
return size.height + somePadding;
}
* Reading property lists
- (id)initWithContentsOfFile:(NSString *)aPath;
- (id)initWithContentsOfURL:(NSURL *)aURL;
* Writing property lists
- (BOOL)writeToFile:(NSString *)aPath atomically:(BOOL)flag;
- (BOOL)writeToURL:(NSURL *)aURL atomically:(BOOL)flag;
* Writing an array to disk
NSArray *array = [NSArray arrayWithObjects:@"Foo", [NSNumber numberWithBool:YES], [NSDate dateWithTimeIntervalSinceNow:60], nil];
[array writeToFile:@"MyArray.plist" atomically:YES];
* Writing a dictionary to disk
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:@"Name", @"Evan", @"Lecture", [NSNumber numberWithInt:9], nil];
[dict writeToFile:@"MyDict.plist" atomically:YES];
* Property list to NSData
+ (NSData *)dataFromPropertyList:(id)plist format:(NSPropertyListFormat)format errorDescription:(NSString *)errorString;
* NSData to property list
+ (id)propertyListFromData:(NSData *)data mutabilityOption:(NSPropertyListMutabilityOptions)opt format:(NSPropertyListFormat *)format errorDescription:(NSString *)errorString;
* Basic directories
NSString *homePath = NSHomeDirectory();
NSString *tmpPath = NSTemporaryDirectory();
* Documents directory
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];
* <Application Home>/Documents/foo.plist
NSString *fooPath = [documentsPath stringByAppendingPathComponent:@"foo.plist"];
* Encode an object for an archive
- (void)encodeWithCoder:(NSCoder *)coder{
[super encodeWithCoder:coder];
[coder encodeObject:name forKey:@"Name"];
[coder encodeInteger:numberOfSides forKey:@"Sides"];
}
* Decode an object from an archive
- (id)initWithCoder:(NSCoder *)coder{
self = [super initWithCoder:coder];
name = [[coder decodeObjectForKey:@"Name"] retain];
numberOfSides = [coder decodeIntegerForKey:@"Sides"];
}
* Creating an archive
NSArray *polygons = ...;
NSString *path = ...;
BOOL result = [NSKeyedArchiver archiveRootObject:polygons toFile:path];
* Decoding an archive
NSArray *polygons = nil;
NSString *path = ...;
polygons = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
* Open the database
int sqlite3_open(const char *filename, sqlite3 **db);
* Execute a SQL statement
int sqlite3_exec(sqlite3 *db, const char *sql, int (*callback)(void*, int, char**, char**), void *context, char **error);
* Close the database
int sqlite3_close(sqlite3 *db);
* Options for parsing XML
libxml2 vs. NSXMLParser
* Reading a JSON string into Foundation objects
#import <JSON/JSON.h>
NSString *jsonString = ...;
id object = [jsonString JSONValue];
* Writing a JSON string from Foundation objects
NSDictionary *dictionary = ...;
jsonString = [dictionary JSONRepresentation];
* Finding (memory) leaks
* Typical NSThread use case
- (void)someAction:(id)sender{
// Fire up a new thread
[NSThread detachNewThreadSelector:@selector(doWork:) withTarget:self object:someData];
}
- (void)doWork:(id)someData{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
[someData doLotsOfWork];
// Message back to the main thread
[self performSelectorOnMainThread:@selector(allDone:) withObject:[someData result] waitUntilDone:NO];
[pool release];
}
* NSLock and subclasses
- (void)someMethod{
[myLock lock];
// We only want one thread executing this code at once
[myLock unlock];
}
* Conditions
// On the producer thread
- (void)produceData{
[condition lock];
newDataExists = YES;
[condition signal];
[condition unlock];
}
// On the consumer thread
- (void)consumeData{
[condition lock];
while(!newDataExists){
[condition wait];
}
newDataExists = NO;
[condition unlock];
}
* Define a custom init method
- (id)initWithSomeObject:(id)someObject{
self = [super init];
if(self){
self.someObject = someObject;
}
return self;
}
* Override - main method to do work
- (void)main{
[someObject doLotsOfTimeConsumingWork];
}
* Using an NSInvocationOperation
- (void)someAction:(id)sender{
NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(doWork:) object:someObject];
[queue addObject:operation];
[operation release];
}
출처 : http://blog.missflash.com/
if([srText isEqualToString:@"mihr01"])
....
else if([srText isEqualToString:@"mihr02"])
....
else
...
문자열이 포함된 것을 찾으려면 (Pos 함수와 비슷)
if([strText rangeOfString:@"mihr01"].length)
if([strText rangeOfString:@"mihr01"].length)
h file...
@interface GlobalTest : NSObject {
NSString *msg;
}
+ (GlobalTest *)sharedSingleton;
m file...
@implementation Conf
static GlobalTest * _globalTest = nil;
- (id) init {
msg = @"Globall Value Test";
}
+(GlobalTest *)sharedSingleton
{
@synchronized([GlobalTest class])
{
if (!_globalTest)
[[self alloc] init];
return _globalTest;
}
return nil;
}
+(id)alloc
{
@synchronized([GlobalTest class])
{
NSAssert(_globalTest == nil, @"Attempted to allocate a second instance of a singleton.");
_globalTest = [super alloc];
return _globalTest;
}
return nil;
}
@interface GlobalTest : NSObject {
NSString *msg;
}
+ (GlobalTest *)sharedSingleton;
m file...
@implementation Conf
static GlobalTest * _globalTest = nil;
- (id) init {
msg = @"Globall Value Test";
}
+(GlobalTest *)sharedSingleton
{
@synchronized([GlobalTest class])
{
if (!_globalTest)
[[self alloc] init];
return _globalTest;
}
return nil;
}
+(id)alloc
{
@synchronized([GlobalTest class])
{
NSAssert(_globalTest == nil, @"Attempted to allocate a second instance of a singleton.");
_globalTest = [super alloc];
return _globalTest;
}
return nil;
}
호출시
#import "GlobalTest.h"
NSLog([[GlobalTest sharedSingleton] msg]);
#import "GlobalTest.h"
NSLog([[GlobalTest sharedSingleton] msg]);
변수에 값을 대입하고 싶으면 프로퍼티 선언 후
[[GlobalTest sharedSingleton] setMsg:@"text"];
[[GlobalTest sharedSingleton] setMsg:@"text"];
int -> NSNumer
NSNumber *anotherNum = [NSNumber numberWithInt: 5];
count = [NSNumber numberWithInt: [count intValue] + 2];
count = [NSNumber numberWithInt: [count intValue] + [anotherNum intValue];
비교문
if([count intValue] == 10) -> true
NSNumber -> int
NSNumber *count=[NSNumber numberWithInt:3];
'I-Phone' 카테고리의 다른 글
[iphone]sqlite (0) | 2010.10.20 |
---|---|
xcode 단축키 (0) | 2010.10.20 |
NSString 문자열 조작 (0) | 2010.09.27 |
[iPhone] URL주소를 가지고 원격지의 이미지 파일을 UIImage로 읽어오기 (0) | 2010.09.23 |
[Objective-C]파일삭제 (0) | 2010.09.23 |