NSDate를 사용하다 보면 unix timestamp형식으로 바꾼다던가, 년/월/일 정보를 가져온다던가 기타 등등 기능이 필요할 때가 있습니다.

그냥 NSDate에서 다 지원해주면 좋겠지만.. 안타깝게 그러진 않네요 -ㅁ-;

NSDate를 다른 형태의 데이터로 변환하는 방법을 정리 해 보았습니다.

1. NSDate to unix timestamp
NSDate의 timeIntervalSince1970를 이용하시면 됩니다.
예: 현재의 시간을 unix timestamp로 변환하기
int timestamp = [[NSDate date] timeIntervalSince1970];


2. unix timestamp to NSDate
NSDate의 dateWithTimeIntervalSince1970:를 이용하시면 됩니다.
예: 2009-06-26 10:51:39의 unix timestamp를 NSDate로 변환하기
NSDate *date = [NSDate dateWithTimeIntervalSince1970:1245981099];


3. NSDate to date component
이건 좀 복잡한데.. 년/월/일 시/분/초 를 구할 때 사용합니다. NSCalendar와 NSDateComponents를 이용하여 구합니다.
예: 2009-06-26 10:51:39의 unix timestamp로 NSDate객체 생성한 뒤 해당 객체를 년/월/일 시/분/초 로 분할하여 표시하기
NSDate *date;
NSDateComponents *com;
    
date = [NSDate dateWithTimeIntervalSince1970:1245980099];
com = [[NSCalendar currentCalendar] components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit) fromDate:date];


4. date component to NSDate
년/월/일 시/분/초 로 부터 NSDate객체를 생성할 때 사용합니다. 마찬가지로 NSCalendar를 이용합니다.
예: 2009-06-26 10:51:39 시간을 가리키는 NSDate객체 생성하기
NSDate *date;
NSDateComponents *com;
NSDateFormatter *formatter;

com = [[NSDateComponents alloc] init];
[com setYear:2009];
[com setMonth:6];
[com setDay:26];
[com setHour:10];
[com setMinute:51];
[com setSecond:39];

date = [[NSCalendar currentCalendar] dateFromComponents:com];

formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSLog(@"%@", [formatter stringFromDate:date]);
[formatter release];
[com release];

크리에이티브 커먼즈 라이센스
Creative Commons License

Posted by 장현준

2009/06/26 11:15 2009/06/26 11:15
, , ,
Response
No Trackback , 4 Comments
RSS :
http://b4you.net/blog/rss/response/231

UIToolbar에는 UIBarButtonItem이 추가될 수 있는데, 기본적으로 추가하게 되면 왼쪽부터 오른쪽까지 왼쪽으로 정렬되어 배치됩니다.
이러한 순서를 변경하여 왼쪽, 오른쪽 또는 가운데로 정렬할 수 있는데 이러한 효과를 주기 위해서는 다음과 같이 코드를 작성합니다.

UIBarButtonItem *flexibleSpaceLeft = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
UIBarButtonItem *flexibleSpaceRight = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
// item은 가운데 정렬할 항목
[_toolbar setItems:[NSArray arrayWithObjects:flexibleSpaceLeft, item, flexibleSpaceRight, nil]];
[flexibleSpaceLeft release];
[flexibleSpaceRight release];


위의 코드와 같이 UIBarButtonSystemItemFlexibleSpace로 생성한 뒤 붙이게 되면 해당 부분은 가변 길이의 공백(?)이 됩니다.
위의 예에서는 가운데 정렬을 하였지만 왼쪽, 오른쪽 정렬을 하기 위해서는 UIBarButtonSystemItemFlexibleSpace로 된 객체를 하나만 만들고 가운데에 넣어주면 됩니다. 다음과 같이 말이죠.

[_toolbar setItems:[NSArray arrayWithObjects:itemLeft, flexibleSpaceCenter, itemRight, nil]];

크리에이티브 커먼즈 라이센스
Creative Commons License

Posted by 장현준

2009/06/16 13:14 2009/06/16 13:14
,
Response
No Trackback , a comment
RSS :
http://b4you.net/blog/rss/response/230

Objective-C gdb로 디버깅 하기

Objective-C를 debug할 때 다음과 같이 break point(이하 bp)를 지정할 수 있습니다.

b -[UIViewController setInterfaceOrientation:]

이렇게 지정한 뒤 실행하면 다음과 같이 중지됩니다.

Pending breakpoint 1 - "-[UIViewController setInterfaceOrientation:]" resolved
(gdb)


bt 명령을 이용하면 call stack를 볼 수 있습니다.

#0  0x3097263a in -[UIViewController setInterfaceOrientation:] ()
#1  0x30978386 in -[UIViewController viewDidMoveToWindow:shouldAppearOrDisappear:] ()
#2  0x309221fb in -[UIView(Internal) _didMoveFromWindow:toWindow:] ()
#3  0x30920883 in -[UIView(Hierarchy) _postMovedFromSuperview:] ()
#4  0x3092079e in -[UIView(Internal) _addSubview:positioned:relativeTo:] ()
#5  0x3091a113 in -[UIView(Hierarchy) addSubview:] ()
.........
(gdb)


#0은 현재 bp 된 위치를 나타내며, bp를 걸었던 UIViewController setInterfaceOrientation: 에서 멈춰있는 것을 볼 수 있습니다.
보통 call stack은 main()부터 시작하며, #<번호> 부분으로 이동하기 위해서는 frame 명령어를 사용합니다. 예를 들어 "#1 -[UIViewController viewDidMoveToWindow:shouldAppearOrDisappear:]" 부분으로 이동하기 위해서는 "frame 1"과 같이 입력합니다. 또는, 현재 위치를 기준으로 +1 되어 있으므로 "up 1"를 입력하여도 됩니다.

"frame 1"로 입력하였을 경우 다음과 같이 현재 위치가 변경됩니다.

(gdb) frame 1
#1  0x30978386 in -[UIViewController viewDidMoveToWindow:shouldAppearOrDisappear:] ()
(gdb)


이 상태에서 인자를 보고 싶을 때 일반 c application은 인자들이 목록에 나와서 display 명령어로 볼 수 있습니다.
이 때 주의할 점은 $ebp레지스터를 이용하기 때문에, 다른 frame의 값은 볼 수 없다는 것 입니다.

(gdb) frame 0
#0  0x3097263a in -[UIViewController setInterfaceOrientation:] ()
(gdb) display *(int *)($ebp + 16)
1: *(int *) ($ebp + 16) = 1
(gdb)


위와 같이 0 frame으로 변경한 뒤, setInterfaceOrientation:의 첫번째 인자를 보면 1로 표시됩니다.
$ebp는 함수 시작 시 설정되는($esp가 저장되어) stack의 시작 주소 이기 때문에 (int *)로 캐스팅 한 뒤 역참조 연산자인 *를 붙여서 정수 값을 출력 하였습니다.
 
일반 c 프로그램을 디버깅 할 때는 display가 유용하지만 Objective-C에서는 다른 방법으로 봐야 합니다. (display로 봐도 되긴 합니다)

(gdb) po _rootView
<UIView: 0xd1a650; frame = (0 0; 320 480); layer = <CALayer: 0xd1a680>>
(gdb)


display를 이용하면 다음과 같이 나옵니다.
(gdb) display _rootView
1: self->_rootView = (UIView *) 0xd1a650
(gdb) display *_rootView
2: *self->_rootView = {
  <UIResponder> = {
    <NSObject> = {
      isa = 0x31a5c620
    }, <No data fields>}, 
  members of UIView: 
  _layer = 0xd1a680, 
  _tapInfo = 0x0, 
  _gestureInfo = 0x0, 
  _gestureRecognizers = 0x0, 
  _charge = 0, 
  _tag = 0, 
  _viewFlags = {
    userInteractionDisabled = 0, 
    implementsDrawRect = 0, 
    implementsDidScroll = 0, 
    implementsMouseTracking = 0, 
    hasBackgroundColor = 0, 
    isOpaque = 1, 
    becomeFirstResponderWhenCapable = 0, 
    interceptMouseEvent = 0, 
    deallocating = 0, 
    debugFlash = 0, 
    debugSkippedSetNeedsDisplay = 0, 
    debugScheduledDisplayIsRequired = 0, 
    isInAWindow = 0, 
    isAncestorOfFirstResponder = 0, 
    dontAutoresizeSubviews = 0, 
    autoresizeMask = 0, 
    patternBackground = 0, 
    fixedBackgroundPattern = 0, 
    dontAnimate = 0, 
    superLayerIsView = 0, 
    layerKitPatternDrawing = 0, 
    multipleTouchEnabled = 0, 
    exclusiveTouch = 0, 
    hasViewController = 0, 
    needsDidAppearOrDisappear = 0, 
    gesturesEnabled = 1, 
    capturesDescendantTouches = 1, 
    deliversTouchesForGesturesToSuperview = 1, 
    chargeEnabled = 0, 
    skipsSubviewEnumeration = 0
  }
}
(gdb)


무엇인가 po가 더 간단해보이죠??? (장, 단점이 있습니다)

디버깅을 Xcode가 다 해준다지만.. 그래도 gdb 정도는 쓸 수 있어야겠죠???
크리에이티브 커먼즈 라이센스
Creative Commons License

Posted by 장현준

2009/06/11 12:55 2009/06/11 12:55
, ,
Response
No Trackback , No Comment
RSS :
http://b4you.net/blog/rss/response/229

C#에서 UNIX_TIMESTAMP 형식 사용하기

UNIX_TIMESTAMP는 1970년 1월 1일 부터 해당 날짜까지 몇 초가 지났는지를 의미한다.
이러한 원리를 알고 있다면 변환하는 방법은 쉽다.
그냥 1970년 1월 1일을 나타내는 DateTime객체를 생성해서 더하거나 빼면 되는 것이다.

이러한 원이를 이용하여 다음과 같은 유틸리티를 만들어두면 편리하다.

public static DateTime DateTimeFromUnixTimeStamp(int unixTimeStamp)
{
    return new DateTime(1970, 1, 1).AddSeconds(unixTimeStamp);
}
public static int UnixTimeStampFromDateTime(DateTime dateTime)
{
    return (int)((dateTime - new DateTime(1970, 1, 1)).TotalSeconds);
}

참 쉽죠잉?
크리에이티브 커먼즈 라이센스
Creative Commons License

Posted by 장현준

2009/06/02 15:23 2009/06/02 15:23
, ,
Response
No Trackback , No Comment
RSS :
http://b4you.net/blog/rss/response/228

C#에서 INI 파싱하기

C#에는 INI parser가 없더군요???
구글링 하다보니... native api로 끌어다 쓰는게 있던데..
최대한 native 쓰지 말자! 라는 생각에 (혹시나 다른 플랫폼에서 돌릴 기회가 있으면 뿌듯해 하려고) 그냥 짰습니다.

덕분에 app header, key, value 등에 ~!@#$%^&*()_+와 같은 문자들을 전부 다 입력해보고.. GetPrivateProfileString()에서 제대로 파싱 되는지 분석해봤습니다.

손가락 2개로 짠거라 버그가 있을지도 모르니 사용하시다가 이상한 점이 있다면 피드백 부탁드립니다. (__)


크리에이티브 커먼즈 라이센스
Creative Commons License

Posted by 장현준

2009/06/01 21:30 2009/06/01 21:30
,
Response
No Trackback , 6 Comments
RSS :
http://b4you.net/blog/rss/response/227

.NET에서 singleton class 만들기

Implementing the Singleton Pattern in C#

The singleton pattern is one of the best-known patterns in software engineering. Essentially, a singleton is a class which only allows a single instance of itself to be created, and usually gives simple access to that instance. Most commonly, singletons don't allow any parameters to be specified when creating the instance - as otherwise a second request for an instance but with a different parameter could be problematic! (If the same instance should be accessed for all requests with the same parameter, the factory pattern is more appropriate.) This article deals only with the situation where no parameters are required. Typically a requirement of singletons is that they are created lazily - i.e. that the instance isn't created until it is first needed.

There are various different ways of implementing the singleton pattern in C#. I shall present them here in reverse order of elegance, starting with the most commonly seen, which is not thread-safe, and working up to a fully lazily-loaded, thread-safe, simple and highly performant version. Note that in the code here, I omit the private modifier, as it is the default for class members. In many other languages such as Java, there is a different default, and private should be used.

All these implementations share four common characteristics, however:

  • A single constructor, which is private and parameterless. This prevents other classes from instantiating it (which would be a violation of the pattern). Note that it also prevents subclassing - if a singleton can be subclassed once, it can be subclassed twice, and if each of those subclasses can create an instance, the pattern is violated. The factory pattern can be used if you need a single instance of a base type, but the exact type isn't known until runtime.
  • The class is sealed. This is unnecessary, strictly speaking, due to the above point, but may help the JIT to optimise things more.
  • A static variable which holds a reference to the single created instance, if any.
  • A public static means of getting the reference to the single created instance, creating one if necessary.

Note that all of these implementations also use a public static property Instance as the means of accessing the instance. In all cases, the property could easily be converted to a method, with no impact on thread-safety or performance.

First version - not thread-safe

// Bad code! Do not use!
public sealed class Singleton
{
    static Singleton instance=null;

    Singleton()
    {
    }

    public static Singleton Instance
    {
        get
        {
            if (instance==null)
            {
                instance = new Singleton();
            }
            return instance;
        }
    }
}

As hinted at before, the above is not thread-safe. Two different threads could both have evaluated the test if (instance==null) and found it to be true, then both create instances, which violates the singleton pattern. Note that in fact the instance may already have been created before the expression is evaluated, but the memory model doesn't guarantee that the new value of instance will be seen by other threads unless suitable memory barriers have been passed.

Second version - simple thread-safety

public sealed class Singleton
{
    static Singleton instance=null;
    static readonly object padlock = new object();

    Singleton()
    {
    }

    public static Singleton Instance
    {
        get
        {
            lock (padlock)
            {
                if (instance==null)
                {
                    instance = new Singleton();
                }
                return instance;
            }
        }
    }
}

This implementation is thread-safe. The thread takes out a lock on a shared object, and then checks whether or not the instance has been created before creating the instance. This takes care of the memory barrier issue (as locking makes sure that all reads occur logically after the lock acquire, and unlocking makes sure that all writes occur logically before the lock release) and ensures that only one thread will create an instance (as only one thread can be in that part of the code at a time - by the time the second thread enters it,the first thread will have created the instance, so the expression will evaluate to false). Unfortunately, performance suffers as a lock is acquired every time the instance is requested.

Note that instead of locking on typeof(Singleton) as some versions of this implementation do, I lock on the value of a static variable which is private to the class. Locking on objects which other classes can access and lock on (such as the type) risks performance issues and even deadlocks. This is a general style preference of mine - wherever possible, only lock on objects specifically created for the purpose of locking, or which document that they are to be locked on for specific purposes (e.g. for waiting/pulsing a queue). Usually such objects should be private to the class they are used in. This helps to make writing thread-safe applications significantly easier.

Third version - attempted thread-safety using double-check locking

// Bad code! Do not use!
public sealed class Singleton
{
    static Singleton instance=null;
    static readonly object padlock = new object();

    Singleton()
    {
    }

    public static Singleton Instance
    {
        get
        {
            if (instance==null)
            {
                lock (padlock)
                {
                    if (instance==null)
                    {
                        instance = new Singleton();
                    }
                }
            }
            return instance;
        }
    }
}

This implementation attempts to be thread-safe without the necessity of taking out a lock every time. Unfortunately, there are four downsides to the pattern:

  • It doesn't work in Java. This may seem an odd thing to comment on, but it's worth knowing if you ever need the singleton pattern in Java, and C# programmers may well also be Java programmers. The Java memory model doesn't ensure that the constructor completes before the reference to the new object is assigned to instance. The Java memory model underwent a reworking for version 1.5, but double-check locking is still broken after this without a volatile variable (as in C#).
  • Without any memory barriers, it's broken in the ECMA CLI specification too. It's possible that under the .NET 2.0 memory model (which is stronger than the ECMA spec) it's safe, but I'd rather not rely on those stronger semantics, especially if there's any doubt as to the safety. Making the instance variable volatile can make it work, as would explicit memory barrier calls, although in the latter case even experts can't agree exactly which barriers are required. I tend to try to avoid situations where experts don't agree what's right and what's wrong!
  • It's easy to get wrong. The pattern needs to be pretty much exactly as above - any significant changes are likely to impact either performance or correctness.
  • It still doesn't perform as well as the later implementations.

Fourth version - not quite as lazy, but thread-safe without using locks

public sealed class Singleton
{
    static readonly Singleton instance=new Singleton();

    // Explicit static constructor to tell C# compiler
    // not to mark type as beforefieldinit
    static Singleton()
    {
    }

    Singleton()
    {
    }

    public static Singleton Instance
    {
        get
        {
            return instance;
        }
    }
}

As you can see, this is really is extremely simple - but why is it thread-safe and how lazy is it? Well, static constructors in C# are specified to execute only when an instance of the class is created or a static member is referenced, and to execute only once per AppDomain. Given that this check for the type being newly constructed needs to be executed whatever else happens, it will be faster than adding extra checking as in the previous examples. There are a couple of wrinkles, however:

  • It's not as lazy as the other implementations. In particular, if you have static members other than Instance, the first reference to those members will involve creating the instance. This is corrected in the next implementation.
  • There are complications if one static constructor invokes another which invokes the first again. Look in the .NET specifications (currently section 9.5.3 of partition II) for more details about the exact nature of type initializers - they're unlikely to bite you, but it's worth being aware of the consequences of static constructors which refer to each other in a cycle.
  • The laziness of type initializers is only guaranteed by .NET when the type isn't marked with a special flag called beforefieldinit. Unfortunately, the C# compiler (as provided in the .NET 1.1 runtime, at least) marks all types which don't have a static constructor (i.e. a block which looks like a constructor but is marked static) as beforefieldinit. I now have a discussion page with more details about this issue. Also note that it affects performance, as discussed near the bottom of this article.

One shortcut you can take with this implementation (and only this one) is to just make instance a public static readonly variable, and get rid of the property entirely. This makes the basic skeleton code absolutely tiny! Many people, however, prefer to have a property in case further action is needed in future, and JIT inlining is likely to make the performance identical. (Note that the static constructor itself is still required if you require laziness.)

Fifth version - fully lazy instantiation

public sealed class Singleton
{
    Singleton()
    {
    }

    public static Singleton Instance
    {
        get
        {
            return Nested.instance;
        }
    }
    
    class Nested
    {
        // Explicit static constructor to tell C# compiler
        // not to mark type as beforefieldinit
        static Nested()
        {
        }

        internal static readonly Singleton instance = new Singleton();
    }
}

Here, instantiation is triggered by the first reference to the static member of the nested class, which only occurs in Instance. This means the implementation is fully lazy, but has all the performance benefits of the previous ones. Note that although nested classes have access to the enclosing class's private members, the reverse is not true, hence the need for instance to be internal here. That doesn't raise any other problems, though, as the class itself is private. The code is a bit more complicated in order to make the instantiation lazy, however.

Performance vs laziness

In many cases, you won't actually require full laziness - unless your class initialization does something particularly time-consuming, or has some side-effect elsewhere, it's probably fine to leave out the explicit static constructor shown above. This can increase performance as it allows the JIT compiler to make a single check (for instance at the start of a method) to ensure that the type has been initialized, and then assume it from then on. If your singleton instance is referenced within a relatively tight loop, this can make a (relatively) significant performance difference. You should decide whether or not fully lazy instantiation is required, and document this decision appropriately within the class. (See below for more on performance, however.)

Exceptions

Sometimes, you need to do work in a singleton constructor which may throw an exception, but might not be fatal to the whole application. Potentially, your application may be able to fix the problem and want to try again. Using type initializers to construct the singleton becomes problematic at this stage. Different runtimes handle this case differently, but I don't know of any which do the desired thing (running the type initializer again), and even if one did, your code would be broken on other runtimes. To avoid these problems, I'd suggest using the second pattern listed on the page - just use a simple lock, and go through the check each time, building the instance in the method/property if it hasn't already been successfully built.

Thanks to Andriy Tereshchenko for raising this issue.

A word on performance

A lot of the reason for this page stemmed from people trying to be clever, and thus coming up with the double-checked locking algorithm. There is an attitude of locking being expensive which is common and misguided. I've written a very quick benchmark which just acquires singleton instances in a loop a billion ways, trying different variants. It's not terribly scientific, because in real life you may want to know how fast it is if each iteration actually involved a call into a method fetching the singleton, etc. However, it does show an important point. On my laptop, the slowest solution (by a factor of about 5) is the locking one (solution 2). Is that important? Probably not, when you bear in mind that it still managed to acquire the singleton a billion times in under 40 seconds. That means that if you're "only" acquiring the singleton four hundred thousand times per second, the cost of the acquisition is going to be 1% of the performance - so improving it isn't going to do a lot. Now, if you are acquiring the singleton that often - isn't it likely you're using it within a loop? If you care that much about improving the performance a little bit, why not declare a local variable outside the loop, acquire the singleton once and then loop. Bingo, even the slowest implementation becomes easily adequate.

I would be very interested to see a real world application where the difference between using simple locking and using one of the faster solutions actually made a significant performance difference.

Conclusion (modified slightly on January 7th 2006)

There are various different ways of implementing the singleton pattern in C#. A reader has written to me detailing a way he has encapsulated the synchronization aspect, which while I acknowledge may be useful in a fewvery particular situations (specifically where you want very high performance, and the ability to determine whether or not the singleton has been created, and full laziness regardless of other static members being called). I don't personally see that situation coming up often enough to merit going further with on this page, but please mail me if you're in that situation.

My personal preference is for solution 4: the only time I would normally go away from it is if I needed to be able to call other static methods without triggering initialization, or if I needed to know whether or not the singleton has already been instantiated. I don't remember the last time I was in that situation, assuming I even have. In that case, I'd probably go for solution 2, which is still nice and easy to get right.

Solution 5 is elegant, but trickier than 2 or 4, and as I said above, the benefits it provides seem to only be rarely useful.

(I wouldn't use solution 1 because it's broken, and I wouldn't use solution 3 because it has no benefits over 5.)

크리에이티브 커먼즈 라이센스
Creative Commons License

Posted by 장현준

2009/05/29 16:27 2009/05/29 16:27
Response
No Trackback , No Comment
RSS :
http://b4you.net/blog/rss/response/226

iPhone 개발 중 Network Indicator(이하 NI)를 사용하다 보면 다음과 같은 경우가 있습니다.

1. thread1에서 network 사용 (NI 켬)
2. thread2에서 network 사용 (NI 켬)
3. thread1이 통신을 마침 (NI 끔)
4. thread2가 통신을 마침 (NI 끔)

이러한 시나리오를 거쳤을 때 UIApplication의 setNetworkActivitryIndicatorVisible값을 변경하는 것 만으로는 문제가 있습니다. 위의 예에서는 3번에서 NI를 껐을 때 thread1은 network를 사용중임에도 불구하고 NI는 꺼져 있는 것으로 나타납니다.

이러한 현상을 해결하기 위해 작성한 singleton class입니다. (singleton class 제작 방법: http://b4you.net/blog/210)

// NetworkActivityManager.h
#import <Foundation/Foundation.h>

@interface NetworkActivityManager : NSObject
{
    volatile NSUInteger _visibleCount;
}

+ (NetworkActivityManager *)sharedNetworkActivityManager;
- (void)setNetworkActivityIndicatorVisible:(BOOL)visible;

@property(readwrite) volatile NSUInteger _visibleCount;

@end


//  NetworkActivityManager.m
#import "NetworkActivityManager.h"

@implementation NetworkActivityManager

@synthesize _visibleCount;

+ (NetworkActivityManager *)sharedNetworkActivityManager
{
    static NetworkActivityManager *networkActivityClass = nil;
    
    if(networkActivityClass == nil)
    {
        @synchronized(self)
        {
            if(networkActivityClass == nil)
            {
                networkActivityClass = [[self alloc] init];
                networkActivityClass._visibleCount = 0;
                [self autorelease];
            }
        }
    }
    
    return networkActivityClass;
}

- (void)setNetworkActivityIndicatorVisible:(BOOL)visible
{
    @synchronized(self)
    {
        if(visible == YES)
        {
            _visibleCount++;
            
            [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
        }
        else if(visible == NO)
        {
            if(_visibleCount <= 1)
            {
                // 모든 곳에서 NO로 했다면
                [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
                _visibleCount = 0;
            }
            else
            {
                // YES로 한 곳이 남아있다면
                _visibleCount--;
            }
        }
    }
}

@end


사용 방법은 다음과 같이~

[[NetworkActivityManager sharedNetworkActivityManager] setNetworkActivityIndicatorVisible:NO];

크리에이티브 커먼즈 라이센스
Creative Commons License

Posted by 장현준

2009/05/21 18:25 2009/05/21 18:25
, ,
Response
No Trackback , a comment
RSS :
http://b4you.net/blog/rss/response/225

iPhone 개발을 하다보니, device에 올려서 NSLog를 출력하면 속도가 급격히 떨어지는 현상을 종종 겪고는 합니다.
실제로 올려서 테스트 하는 경우도 있지만 보통은 simulator에서 열심히 디버깅을 하고 device에 올려서 최종 테스트를 하고.. 이런 과정을 거쳐서 개발을 하는데요, 이럴때 device에 올렸을때만 로그가 안찍히게 할 수 있는 방법을 소개해드립니다.

iPhone simulator에서 동작을 할 때에는 "TARGET_IPHONE_SIMULATOR" 값이 자동으로 define됩니다.
이 define된 것을 이용하여 조건부 컴파일을 하여 simulators 일때만 로그를 남길 수 있게 할 수 있습니다. 예를 들면 다음과 같이 말이죠.

#define USE_CONDITIONAL_LOG

#ifdef USE_CONDITIONAL_LOG
	#if TARGET_IPHONE_SIMULATOR
		#define ConditionalNSLog			NSLog
	#else
		#define ConditionalNSLog			(void)
#else
	#define ConditionalNSLog				NSLog
#endif

위와 같이 선언한 뒤 실제 코드에는 다음과 같이 이용합니다.

ConditionalNSLog(@"hello~");
크리에이티브 커먼즈 라이센스
Creative Commons License

Posted by 장현준

2009/05/21 09:26 2009/05/21 09:26
,
Response
No Trackback , No Comment
RSS :
http://b4you.net/blog/rss/response/224

javascript 안에서 & 사용하기

XML형태로 되어 있는 html 문서에 다음과 같이 javascript를 입력하면 성공적인 validate가 되지 않는다

<script language="Javascript">
document.location = "abcd?a=1&b=2";
</script>

이러한 현상을 해결하기 위해서는 다음과 같이 CDATA 로 감싸주면 된다.

<script language="Javascript">//<![CDATA[
document.location = "abcd?a=1&b=2";
//]]></script>
크리에이티브 커먼즈 라이센스
Creative Commons License

Posted by 장현준

2009/05/12 16:15 2009/05/12 16:15
Response
No Trackback , No Comment
RSS :
http://b4you.net/blog/rss/response/223

TLS 변수 초기화 하기

TLS(Thread Local Storage)를 사용하기 위해 변수를 초기화 하려면 다음과 같은 방법을 이용하면 됩니다.

1. API 사용
DWORD dwTlsIndex;
LPVOID pData;

dwTLSIndex = TlsAlloc();

if(dwTLSIndex != TLS_OUT_OF_INDEXES)
{
	pData = (LPVOID)LocalAlloc(LPTR, 256);

	TlsSetValue(dwTlsIndex, pData);

	TlsFree(dwTlsIndex);

	CommonFunc();

	pData = TlsGetValue(dwTlsIndex);

	if(pData != NULL)
	{
		LocalFree((HLOCAL)pData);
	}
}


2. compiler keyword 사용
_declspec(thread) int g_nCount;

2번의 경우 .tls section을 이용하여 구현이 된다고 하는데, 방법이 더 쉽긴 하지만 dll의 경우 process에 attach/detach될 때 문제가 발생할 수 있기 때문에 1번을 사용하여야 된다고 합니다.
크리에이티브 커먼즈 라이센스
Creative Commons License

Posted by 장현준

2009/05/11 20:07 2009/05/11 20:07
Response
No Trackback , No Comment
RSS :
http://b4you.net/blog/rss/response/222

« Previous : 1 : 2 : 3 : 4 : 5 : 6 : 7 : 8 : ... 25 : Next »

블로그 이미지

빗소리를 먹는 사람.

- 장현준

Notices

Archives

Authors

  1. 장현준

Recent Trackbacks

Calendar

«   2017/09   »
          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 30

Site Stats

Total hits:
1714554
Today:
3709
Yesterday:
3980