블로그 이미지
서비
나의 삶을 디자인 한다.

calendar

      1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29      

Notice

'Code Library'에 해당되는 글 12

  1. 2010/07/28 아이폰 개발 예제들
  2. 2010/07/28 NSString 을 int 로 변환하기
  3. 2010/07/28 NSString 문자열 비교(1)
  4. 2010/07/28 전역변수 사용법 - 싱글톤
  5. 2010/07/28 NSNumber 활용법(1)
  6. 2010/05/17 UIImageView URL로 로드하기
  7. 2007/04/27 UTF8 Encode
  8. 2007/01/19 URL 인코딩
  9. 2007/01/19 컴퓨터 이름 가져오기
  10. 2007/01/19 HttpGet
2010/07/28 22:39 Code Library/Objective C
* 특정 포맷의 문자열 작성
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 = @(name);
SEL anotherSelector = @(setName:);
SEL lastSelector = @(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:@(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 allocinit];

* 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
@ 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
@ UIControl;
- (void)addTarget:(id)target action:(SEL)action forControlEvents:(UIControlEvents)controlEvents;
- (void)removeTarget:(id)target action:(SEL)action forControlEvents:(UIControlEvents)controlEvents;





> 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:@(foo:)];
self.navigationItem.leftBarButtonItem = fooButton;
[fooButton release];
}

* System bar button item
- (void)viewDidLoad{
UIBarButtonItem *addButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd style:UIBarButtonItemStyleBordered target:self action:@(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:navControlleranotherNavControllersomeViewController, 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
@ UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView;
...
- (BOOL)scrollViewShouldScrollToTop:(UIScrollView *)scrollView;

* 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;
@(nonatomic,readonly) NSUInteger section;
@(nonatomic,readonly) NSUInteger row;

* 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:@(doWork:) withTarget:self object:someData];
}

- (void)doWork:(id)someData{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
[someData doLotsOfWork];

// Message back to the main thread
[self performSelectorOnMainThread:@(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:@(doWork:) object:someObject];
[queue addObject:operation];
[operation release];
}

출처 : http://blog.missflash.com/
posted by 서비
2010/07/28 13:25 Code Library/Objective C

NSString를 int로 변환 하는 방법.


NSString *nStr;
nStr = @"16";
int j = [nStr intValue];



int를 NSString로 변환 하는 방법.

int j = 0;
NSString *nStr = [NSString stringWithFormat:@"%d",j];

posted by 서비
2010/07/28 13:21 Code Library/Objective C

NSString *strText = idField.text;
if([srText isEqualToString:@"mihr01"])
....
else if([srText isEqualToString:@"mihr02"])
....
else
...

문자열이 포함된 것을 찾으려면 (Pos 함수와 비슷)
if([strText rangeOfString:@"mihr01"].length) 
posted by 서비
2010/07/28 13:19 Code Library/Objective C
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;
}

호출시
#import "GlobalTest.h"

NSLog([[GlobalTest sharedSingleton] msg]);

변수에 값을 대입하고 싶으면 프로퍼티 선언 후
[[GlobalTest sharedSingleton] setMsg:@"text"];
posted by 서비
2010/07/28 12:52 Code Library/Objective C
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];
posted by 서비
2010/05/17 01:02 Code Library/Objective C
UIImageView *tempImageView = [[UIImageView alloc] initWithImage:[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://www.abc.com/image.png"]]]];
posted by 서비
2007/04/27 10:53 Code Library/Win32 API

int MultibyteToUTF8(const char* src,int nbyte,char** dest)
{
    unsigned short* unicode=NULL;
    int strlen = UNICODE_encode(src,nbyte,&unicode);
    int ret = UTF8_encode(unicode,strlen,dest);
    delete[] unicode;
    return ret;
}

int UNICODE_encode(const char* src,int bytelen,unsigned short** unicode)
{
    if(src == NULL || bytelen == 0 || IsBadReadPtr(src,bytelen) == TRUE) 
    {
        *unicode = NULL;
        return 0;   
    }
    int nLen = MultiByteToWideChar(CP_ACP,0,src,bytelen,NULL,NULL);
    
    if(nLen == 0) 
    {
        *unicode = NULL;
        return 0;
    }

    *unicode = new unsigned short[nLen+1];
    if(*unicode == NULL || IsBadWritePtr(*unicode,(nLen+1)*sizeof(unsigned short)) == TRUE) 
    {
        *unicode = NULL;
        return 0;
    }

    ZeroMemory(*unicode,nLen*sizeof(unsigned short)+2);
    MultiByteToWideChar(CP_ACP,0,src,bytelen,*unicode,nLen);
    return nLen;
}

int UTF8_encode(const unsigned short* src,int srclen,char** multibyte)
{
    if(src == NULL || srclen == 0 || IsBadReadPtr(src,srclen*sizeof(unsigned short)) == TRUE) 
    {
        *multibyte = NULL;
        return 0;   
    }

    int nLen = WideCharToMultiByte(CP_UTF8,0,src,srclen,*multibyte,0,NULL,NULL);
    
    if(nLen == 0) 
    {
        *multibyte = NULL;
        return 0;
    }

    *multibyte = new char[nLen+1];

    if(*multibyte == NULL || IsBadWritePtr(*multibyte,nLen+1) == TRUE) 
    {
        *multibyte = NULL;
        return 0;
    }

    ZeroMemory(*multibyte,nLen+1);
    WideCharToMultiByte(CP_UTF8,0,src,srclen,*multibyte,nLen,NULL,NULL);
    return nLen;
}


int UTF8ToMultibyte(const char* src,int nbyte,char** dest)
{
    unsigned short* unicode=NULL;
    int strlen = UTF8_decode(src,nbyte,&unicode);
    int ret = UNICODE_decode(unicode,strlen,dest);
    delete[] unicode;
    return ret;
}


int UNICODE_decode(const unsigned short* src,int srclen,char** multibyte)
{
    if(src == NULL || srclen == 0 || IsBadReadPtr(src,srclen*sizeof(unsigned short)) == TRUE) 
    {
        *multibyte = NULL;
        return 0;   
    }
    
    int nLen = WideCharToMultiByte(CP_ACP,0,src,srclen,*multibyte,0,NULL,NULL);

    if(nLen == 0) 
    {
        *multibyte = NULL;
        return 0;
    }

    *multibyte = new char[nLen+1];

    if(*multibyte == NULL || IsBadWritePtr(*multibyte,nLen+1) == TRUE) 
    {
        *multibyte = NULL;
        return 0;
    }

    ZeroMemory(*multibyte,nLen+1);
    WideCharToMultiByte(CP_ACP,0,src,srclen,*multibyte,nLen,NULL,NULL);
    return nLen;
}


int UTF8_decode(const char* src,int bytelen,unsigned short** unicode)
{
    
    if(src == NULL || bytelen == 0 || IsBadReadPtr(src,bytelen) == TRUE) 
    {
        *unicode = NULL;
        return 0;   
    }

    int nLen = MultiByteToWideChar(CP_UTF8,0,src,bytelen,NULL,NULL);

    if(nLen == 0) 
    {
        *unicode = NULL;
        return 0;
    }

    *unicode = new unsigned short[nLen+1];

    if(*unicode == NULL || IsBadWritePtr(*unicode,(nLen+1)*sizeof(unsigned short)) == TRUE) 
    {
        *unicode = NULL;
        return 0;
    }

    ZeroMemory(*unicode,nLen*sizeof(unsigned short)+2);
    MultiByteToWideChar(CP_UTF8,0,src,bytelen,*unicode,nLen);
    return nLen;
}
posted by 서비
TAG Unicode, UTF-8
2007/01/19 15:22 Code Library/C/C++

// HEX Values array
char hexVals[16] = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};





// UNSAFE String
CString CURLEncode::csUnsafeString= "\"<>%\\^[]`+$,@:;/!#?=&"; // PURPOSE OF THIS FUNCTION IS TO CONVERT A GIVEN CHAR TO URL HEX FORM CString CURLEncode::convert(char val) { CString csRet; csRet += "%"; csRet += decToHex(val, 16); return csRet; } // THIS IS A HELPER FUNCTION. // PURPOSE OF THIS FUNCTION IS TO GENERATE A HEX REPRESENTATION OF GIVEN CHARACTER CString CURLEncode::decToHex(char num, int radix) { int temp=0; CString csTmp; int num_char; num_char = (int) num; // ISO-8859-1 // IF THE IF LOOP IS COMMENTED, THE CODE WILL FAIL TO GENERATE A // PROPER URL ENCODE FOR THE CHARACTERS WHOSE RANGE IN 127-255(DECIMAL) if (num_char < 0) num_char = 256 + num_char; while (num_char >= radix) { temp = num_char % radix; num_char = (int)floor(num_char / radix); csTmp = hexVals[temp]; } csTmp += hexVals[num_char]; if(csTmp.GetLength() < 2) { csTmp += '0'; } CString strdecToHex(csTmp); // Reverse the String strdecToHex.MakeReverse(); return strdecToHex; } // PURPOSE OF THIS FUNCTION IS TO CHECK TO SEE IF A CHAR IS URL UNSAFE. // TRUE = UNSAFE, FALSE = SAFE bool CURLEncode::isUnsafe(char compareChar) { bool bcharfound = false; char tmpsafeChar; int m_strLen = 0; m_strLen = csUnsafeString.GetLength(); for(int ichar_pos = 0; ichar_pos < m_strLen ;ichar_pos++) { tmpsafeChar = csUnsafeString.GetAt(ichar_pos); if(tmpsafeChar == compareChar) { bcharfound = true; break; } } int char_ascii_value = 0; //char_ascii_value = __toascii(compareChar); char_ascii_value = (int) compareChar; if(bcharfound == false && char_ascii_value > 32 && char_ascii_value < 123) { return false; } // found no unsafe chars, return false else { return true; } return true; }
// PURPOSE OF THIS FUNCTION IS TO CONVERT A STRING // TO URL ENCODE FORM. CString CURLEncode::URLEncode(CString pcsEncode) { int ichar_pos; CString csEncode; CString csEncoded; int m_length; int ascii_value; csEncode = pcsEncode; m_length = csEncode.GetLength(); for(ichar_pos = 0; ichar_pos < m_length; ichar_pos++) { char ch = csEncode.GetAt(ichar_pos); if (ch < ' ') { ch = ch; } if(!isUnsafe(ch)) { // Safe Character csEncoded += CString(ch); } else { // get Hex Value of the Character csEncoded += convert(ch); } } return csEncoded; } CString CURLDecoder::decode(CString str) { int len = str.GetLength(); char* buff = new char[len + 1]; strcpy(buff,str); CString ret = ""; for(int i=0;i<len;i++) { if(buff[i] == '+') { ret = ret + " "; }else if(buff[i] == '%') { char tmp[4]; char hex[4]; hex[0] = buff[++i]; hex[1] = buff[++i]; hex[2] = '\0'; //int hex_i = atoi(hex); sprintf(tmp,"%c",convertToDec(hex)); ret = ret + tmp; }else { ret = ret + buff[i]; } } delete[] buff; return ret; } int CURLDecoder::convertToDec(const char* hex) { char buff[12]; sprintf(buff,"%s",hex); int ret = 0; int len = strlen(buff); for(int i=0;i<len;i++) { char tmp[4]; tmp[0] = buff[i]; tmp[1] = '\0'; getAsDec(tmp); int tmp_i = atoi(tmp); int rs = 1; for(int j=i;j<(len-1);j++) { rs *= 16; } ret += (rs * tmp_i); } return ret; } void CURLDecoder::getAsDec(char* hex) { char tmp = tolower(hex[0]); if(tmp == 'a') { strcpy(hex,"10"); }else if(tmp == 'b') { strcpy(hex,"11"); }else if(tmp == 'c') { strcpy(hex,"12"); }else if(tmp == 'd') { strcpy(hex,"13"); }else if(tmp == 'e') { strcpy(hex,"14"); }else if(tmp == 'f') { strcpy(hex,"15"); }else if(tmp == 'g') { strcpy(hex,"16"); } }
posted by 서비
TAG HTTP, URL
2007/01/19 11:18 Code Library/Win32 API
char    szBuffer[MAX_COMPUTERNAME_LENGTH + 1];
DWORD   dwNameSize = MAX_COMPUTERNAME_LENGTH + 1;

GetComputerName(szBuffer, &dwNameSize);

posted by 서비
TAG Win32 API
2007/01/19 10:59 Code Library/VC++
const INT BUF_SIZE = 2048576;
TCHAR g_pBuffer[BUF_SIZE] = {0};

// 지정된 URL(strURL) 에서 소스코드를 얻는다(strSourceCode)

BOOL HttpGet(const CString& strURL, CString& strSourceCode)
{
    HINTERNET hInternet;
    hInternet = InternetOpen(_T("GBHConnect"), INTERNET_OPEN_TYPE_DIRECT, 0, 0, 0);

    if( hInternet == NULL )
    {
        ASSERT(0);
        return FALSE;
    }

    CString strHeader = _T("Accept: */*\'\r\n\'Accept-Charset: ks_c_5601-1987\'\r\n\'");
    strHeader += _T("Accept-Language: ko\'\r\n\'Content-Encoding: ks_c_5601-1987");

    HINTERNET hInternetRequest;
    hInternetRequest = InternetOpenUrl( hInternet, strURL, strHeader, 0, INTERNET_FLAG_RELOAD, 0 );
    if( NULL == hInternetRequest )
    {
        ASSERT(0);
        return FALSE;
    }

    strSourceCode = _T("");
    BOOL bOK;

    const INT READ_SIZE = 10240;

    DWORD dwTotalReadByte = 0;
    while( TRUE )
    {
        DWORD dwNumOfBytesRead;
        bOK = InternetReadFile( hInternetRequest, &g_pBuffer[dwTotalReadByte], READ_SIZE, &dwNumOfBytesRead);
        if( FALSE == bOK ||  0 == dwNumOfBytesRead )
        {
            break;
        }
        dwTotalReadByte += dwNumOfBytesRead;


        if( bOK == FALSE )
        {
            ASSERT(0);
            InternetCloseHandle( hInternetRequest );
            InternetCloseHandle( hInternet );
            return FALSE;
        }
    }
    InternetCloseHandle( hInternetRequest );
    InternetCloseHandle( hInternet );

    g_pBuffer[dwTotalReadByte+1] = '\0';
    strSourceCode = g_pBuffer;

    return TRUE;
}
posted by 서비
TAG HTTP
prev 1 2 next