2010년 8월 10일 화요일

[iPhone] Tip & Tech

< NSThread>

화면 처리는 무조건 메인스레드를 이용하라! (특히 UIProgressView를 쓸때 많이 사용한다.)
[self performSelectorOnMailThread:@selector(aaa) withObject:nil waitUntilDone:YES];


<  Regular Expressions in Objective-C >

NSString *str = @"1234abcd";

NSString *ptn = @"[a-z]";

 

NSRange range = [str rangeOfString:ptn options:NSRegularExpressionSearch];


[출처 : http://cafe.naver.com/mcbugi/70323]

[iPhone] UIImage에 imageNamed

UIImage에 imageNamed Method (http://cafe.naver.com/mcbugi/71591)

UIImage의 imageNamed의 특징은 단순히 이름으로 파일을 열어서 이미지를 불러오지만 캐싱한다는 점이 있습니다. 이 캐싱은 장단점이 있습니다.


문제는 한번 로드하면 해제를 안합니다.


본문을 캡쳐 해 온 것인데.. imageNamed는 한번 로드하면 (어플이 죽기 전까지) 해제를 하지 않는 다는게
큰 문제지요.. 뭐.. 데스크탑이라면 전혀 문제 될것이 없지만.. 모바일 기기에는 한정이 되어 있는 메모리가 있으므로.. 문제가 되지요. (느려진다거나 메모리 부족으로 죽는다는 현상)

그래서.. 친절한 문씨님께서는.. 해결책도 적어 두셨습니다.

//UIImageExtension.h

@interface UIImage (UIImageExtension)

+ (UIImage *)imageNamed:(NSString *)name forSession:(id)session;

+ (void)clearSession:(id)session;

@end


헤더에는 이것뿐입니다. 다른 함수는 알 필요가 없죠


//UIImageExtension.m

#import “UIImageExtension.h”


@implementation UIImage (UIImageExtension)

static NSMutableDictionary *__imageSessions;


+ (NSMutableDictionary *)_imageSessions {

        if (__imageSessions == nil) {

            __imageSessions = [[NSMutableDictionary alloc] init];

        }

        return __imageSessions;

}


+ (NSMutableDictionary *)_sessionForKey:(NSString *)key {

        NSMutableDictionary *data = [self _imageSessions];

        NSMutableDictionary *session = [data objectForKey:key];

        if (session == nil) {

                session = [NSMutableDictionary dictionary];

                [data setObject:session forKey:key];

        }

        return session;

}

+ (UIImage *)_findImageWithName:(NSString *)name {

        NSArray *sessionKeys = [__imageSessions allKeys];

        UIImage *image = nil;

        for (int i = 0; i < [sessionKeys count] && image == nil; i++) {

                NSMutableDictionary *session = [__imageSessions objectForKey:[sessionKeys objectAtIndex:i]];

                image = [session objectForKey:name];

        }

        return image;

}


+ (UIImage *)imageNamed:(NSString *)name forSession:(id)session {

        NSString *key = [NSString stringWithFormat:@”%p”,session];


        NSMutableDictionary *sessionContainer = [self _sessionForKey:key];


        UIImage *image = [sessionContainer objectForKey:name];


        if (image != nil) {

                return image;

        } else {

                image = [self _findImageWithName:name]; //다른곳에 등록된 이미지를 찾는다


                if (image == nil) {

                        NSString *path = [[NSBundle mainBundle] pathForResource:name ofType:nil];

                        if (path != nil) {

                                image = [UIImage imageWithContentsOfFile:path];                                

                        }

                }

                if (image != nil) {

                         [sessionContainer setObject:image forKey:name];

                }


        }

        return image;

}


+ (void)clearSession:(id)session {

        if (session == nil) return;

        NSString *key = [NSString stringWithFormat:@”%p”,session];

        [__imageSessions removeObjectForKey:key];

}


@end

[출처] [문씨의 강좌adkf] 메모리 관리3 <Singleton> (맥부기 아이폰(iPhone)OS 개발자모임) |작성자 문씨


위와 같은 Category를 만들어서 사용한다면.. 조금이나마 메모리 관리를 효율 적으로 할 수 있지 않을까?

2010년 4월 6일 화요일

[iphone] view 접근

뷰는 만들었는데...
아.. 이것을 맴버로 빼기엔.. 사용량이 적고..
그냥 View에 넣기엔.. 한번 정도는 사용하고..

이럴땐.. 다음과 같이 먼저 View에 넣은 후 Release를 하고..
그 놈을 찾아 들어가자! ㅎㅎㅎ

for (UIButton *obj in self.view.subviews) {
       
if ([obj isMemberOfClass:[UIButton class]]) {
               
[UIView beginAnimations:nil context:NULL];
               
[UIView setAnimationDuration:1];
               
[UIView setAnimationTransition:UIViewAnimationTransitionFlipFromRight forView:obj cache:YES];//~~self.view cache:YES];                          
                obj
.hidden = NO;
               
[UIView commitAnimations];
       
}
   
}
   
[gridTimer invalidate];


더 확실 하게 찾는 방법은?

View안에 넣기전.. 이름표(tag)를 붙여주면? ㅎㅎㅎㅎㅎ

[iPhone] CoreAnimation

CoreAnimation

 

ㅎㅎ 에니메이션은 다른 말이 필요 없을 듯...


이 예제 한방이면.. 모든게..


최강의 예제...

2010년 4월 4일 일요일

[iPhone] UITabbarcontroller의 UITabbarItem 선택된 색상 바꾸기

기본적으로 제공하는 UITabbarcontroller에서 하단 탭바의 선택 색깔은 Blue 이다.

Blue 색을 바꾸기 위해서...는 다음과 같이 하면 된다.

// 각 탭바에 선택 되기전 이미지(menuOne), 선택되었을 때 이미지(menuOne_select)를 만들고,
// 각 이미지를 넣어주면 된다.
// 이미지를 수정 없이 넣으면 이미지가 상단으로 올라가므로 tabBarSelectedImageLocationMove
// 메소드를 통해서 수정 9.0f 정도 밑으로 내려주면~ 끝 ㅎ

UIImage *menuOne = [UIImage imageNamed:@"images/common/menu1.png"];

UIImage *menuOne_select = [UIImage imageNamed:@"images/common/menu1_on.png"];

[basicSubNavController.tabBarItem setTitle:@"아웃~ㅎ"];

[basicSubNavController.tabBarItem setImage:[self tabBarSelectedImageLocationMove:menuOne]];

[basicSubNavController.tabBarItem setSelectedImage:[self tabBarSelectedImageLocationMove:menuOne_select]];

[basicSubNavController.tabBarItem setTag:0];


// 이미지가 상단으로 이동 되므로 아래로 내려 주는 메소드

- (UIImage *)tabBarSelectedImageLocationMove:(UIImage *)_image

{

UIImage *itemImage;

CGSize itemImageSize = [_image size];

UIGraphicsBeginImageContext(itemImageSize);

CGContextSetInterpolationQuality(UIGraphicsGetCurrentContext(), kCGInterpolationHigh);

[_image drawInRect:CGRectMake(0.0f, 9.0f,

itemImageSize.width, itemImageSize.height)];

itemImage = UIGraphicsGetImageFromCurrentImageContext();

UIGraphicsEndImageContext();

return itemImage;

}


==== 추가 사항 ====

원래 TabbarItem에는 setSelectedImage 라는 메소드는 없다.

그럼 어떻게??


UIBarExtend.h & UIBarExtend.m 파일을 만든다. (NSObject)


UIBarExtend.h

@interface UITabBar (ColorExtensions)

- (void)fixTabBarBackground;

@end


@interface UITabBarItem (Private)

@property(retain, nonatomic) UIImage *selectedImage;


@end

UIBarExtend.m

#import "UITabbar_Extension.h"


@implementation UITabBar (ColorExtensions)


// 이건.. 탭바 배경 바꾸는 소스 ㅎㅎㅎ

- (void)fixTabBarBackground

{

UIImage *img = [UIImage imageNamed:@"bg_foot.png"];

UIImageView *imgView = [[UIImageView alloc] initWithImage:img];

[self addSubview:imgView];

[imgView release];

}

@end



진작 이렇게 할껄...ㅎ

괜히

http://stackoverflow.com/questions/2506290/how-to-change-uitabbar-selected-color

이거 보고 따라했다가.. 리젝 먹었음;;;

2010년 3월 11일 목요일

[iPhone] Debug

[상황]

UIWebView로 화면을 Rotate했을 때 발생하는 버그.


[Debug]

malloc: *** error for object 0x2891000: pointer being freed was not allocated

*** set a breakpoint in malloc_error_break to debug


다음과 같은 디버그는.. Simulator SDK 3.0에서 발생하는 버그다.


[해결]

SDK를 3.0 -> 3.1로 변경.



[참고 URL]

http://stackoverflow.com/questions/1424210/iphone-development-pointer-being-freed-was-not-allocated

==============================================================================


[상황]

In App Purchase 상태에서 구매 하려 할 때...


[Debug]

Error Domain=SKErrorDomain Code=0 UserInfo=0x297f00 "Cannot connect to iTunes Store"


[해결]

In App Purchase를 on 하기 전에 했던 프로파일을 사용한 경우 발생.

In App Purchase on  및 새로운 장비 등록 후에는 잊지 말고 프로파일을 변경하여 적용

시켜주자! 즉, 프로파일을 다시 받아서 적용 시키면 됨. ㅎ