Archive for the ‘Cocoa’ Category

Raw Key Code for Function Keys

I figure out key codes for function keys from F1 to F12 on Mac.

  • F1 : 122
  • F2 : 120
  • F3 : 99
  • F4: 118
  • F5: 96
  • F6: 97
  • F7: 98
  • F8: 100
  • F9: 101
  • F10: 109
  • F11: 103
  • F12: 111

They are not related to ASCII table at all.
Code marked as ‘solution’ or ‘answer’ here doesn’t care of them. They are all converted to a printable characters, ^P. So, a table created with the method in the StackOverflow can’t differentiate each of the function keys. So, if you want to differentiate them, customize value saved there using the table above.

It turned out that the database solution, 4D, also had such values for the function keys.
So, it says that the values above is not only specific to my keyboard, Logitech  K760.

(It’s surprising that 4D is still alive.)

Whether to call [super mouseDown:] etc or not

From View Programming Guide : Handling Mouse Click and Dragging Events

Notice that the mouseDown: implementation in Listing 4-7 does not call the super implementation. The NSView class’s default implementation for the mouse handling events are inherited from NSResponder and pass the event up the responder chain for handling, bypassing the view in question entirely. Typically a custom NSView subclass should not call the super implementation of any of the mouse-event methods.

Once [super mouseDown:…] is called, mouseDragged: is not called. mouseMoved: can be still received by calling [[self window] setAcceptsMouseMovedEvents:YES]; though.

So, for custom views which needs to handle all details of mouse event, it’s better not to call super’s messages of NSResponder, in other words, mouseDown, mouseUp, mouseDragged, mouseMoved, etc.

There is different results obtained by different combination of acceptsFirstResponder, acceptsFirstMouse etc. So, when implementing mouse event handler, please consider situation thoroughly and test as many as cases you can imagine. ( Hmmmm… S/W engineers who are not considerate tend to think that they know everything and ignore general situation.. So, I wonder if this recommendation would be effective to them. )

객체 소유를 strong으로 할 것이냐 weak으로 할 것이냐? 그 새로운 시작

이미 이 주제에 대해선 몇번 언급을 했다. 그리고 항상 헷갈리고.

더군다나 OS X에선 특정 인터페이스는 strong이나 assign으로만 해야 하는 것도 있고. (ARC가 활성화 되었어도, assign으로!)

OS X에서 iOS 프로그래밍까지 더 하기 시작했을 때, 둘 사이에 이게 달라 무지하게 헷갈렸다. 더군다나 Xcode의 Interface Builder 모듈도 종종 버그도 있고 해서, 그 놈이 기본으로 설정해 주는 것을 믿기도 힘들고.

그래도 다행스러웠던 점은, 애플이 iOS와 Mac OS X간의 차이를 해소하려 했다는 것이다.
이제 스토리보드가 Mac에도 사용되기 시작함으로써, 그 내재된 구조적 차이는 해소되어 가는 것 같다.

자. 이 문제를 갱신해 보자. 요번엔 애플의 문서에 무엇이 top object인지 좀 더 명확한 정의가 내려져 있다. (정말 이전엔 헷갈렸다. 알고 있다가도 또 보면 모르겠고.)

When your program loads a nib file, Cocoa recreates the entire graph of objects you created in Xcode. This object graph includes all of the windows, views, controls, cells, menus, and custom objects found in the nib file. The top-level objects are the subset of these objects that do not have a parent object. The top-level objects typically include only the windows, menubars, and custom controller objects that you add to the nib file. (Objects such as File’s Owner, First Responder, and Application are placeholder objects and not considered top-level objects.)

Resource Programming  Guide : Nib Files
From a practical perspective, in iOS and OS X outlets should be defined as declared properties. Outlets should generally be weak, except for those from File’s Owner to top-level objects in a nib file (or, in iOS, a storyboard scene) which should be strong. Outlets that you create should therefore typically be weak, because:

Xcode 6.1이 가져온 큰 변화 (Integration of iOS & Mac OS X for programmers )

놀랍게도 내가 보기엔 Swift가 아니다.

Xcode 6.1이 가져온 큰 변화는 드디어 Mac에서도 iOS의 View Controller를 쓸 수 있다는 것.
이렇게 함으로써 주가 되는 뷰들을 각각의 xib에 넣고 관리하게끔 유도한다. (물론 그 xib들을 storyboard로 관계 맺어주는 것이지. 사실 storyboard의 등장은 xib를 없앤게 아니다. 스토리보드 파일을 열어보면 그 답이 나온다.)
당연히 덩치가 큰 프로그램은 메모리 사용량 관리에서 더 좋아질테고. 이렇게 함으로써 사실상 Mac과 iOS의 가장 큰 차이점이 없어지게 되었다. 물론 프레임워크의 차이야 조금은 있지만, 그건 마치 다른 버젼의 프레임웍 같은 느낌이고.. 사용 패턴등에 대해선 차이가 없다.

자. 이제 맥에서도 NSView가 NSWindow의 상위에 놓일지는 의문이다. 그렇게 되면 프로그래밍적으로 iOS와 OS X의 통합이 될거다.
NS*대신 UI*를 사용할텐데, 어느 쪽으로 통합될까? 혹 UI*는 아닐까? NS는 NextStep의 흔적이니까.

그래도 난 NS가 좋다. 왠지 UI*는 뭐랄까.. 히피같은 느낌?

그리고 iOS에선 Core Foundation 혹은 그 레벨에 준하는 것들을 Foundation보다 더 많이 사용하는데 (UIColor vs. CGColor) 앞으로 iOS 이전의 프레임워크처럼 CF*에 해당하는 해당하는 것에 대응하는 UI*를 빨리 빨리 만들어 주었으면 하는 바램이다.

Without creating help files using Doxygen/HeaderDoc, Xcode 5에선 자동으로 Quick Help에 코멘트를 보여줍니다.

“structured comments in your own source code are displayed in the quick help panel and in code completion popover views. Doxygen and HeaderDoc structured comments are supported formats.”

converting frame image data in CVImageBufferRef to PNG

This StackOverflow explains how to convert a video frame image in CVImageBufferRef to PNG through CIImage of Core Image and CGImageRef of Core Graphics.
Of course, it can be also changed to NSImage and do whatever you want there too.
(toll-free bridging between Core* and NS*.. :). But in this case, there are some more chores to do manually. )

Saving NSImage as JPEG ( or anything else)

// Output as JPEG
NSImage *image4 = [[NSImage alloc] initWithSize:NSMakeSize(320.0f, 240.0f)];
[image4 lockFocus];

[[NSColor redColor] setFill];
[[NSColor blueColor] setStroke];

[rectPath setLineWidth:10.0f];
[rectPath stroke];
[rectPath fill];

//        NSArray *representations = [image4 representations];
//        NSData *jpegData = [NSBitmapImageRep representationOfImageRepsInArray:representations
//                                                                    usingType:NSJPEGFileType
//                                                                   properties:[NSDictionary dictionaryWithObjectsAndKeys:@0.8f, NSImageCompressionFactor, nil]];

// Code above doesn't work.
//        (lldb) po representations
//        <__NSArrayI 0x104801d10>(
//                                 <NSCGImageSnapshotRep:0x104802fe0 cgImage=<CGImage 0x104802f00>>
//                                 )
// the presentation doesn't return an appropriate instance of NSImageRep concrete interface.

NSBitmapImageRep *jpegImageRep = [[NSBitmapImageRep alloc] initWithFocusedViewRect:NSMakeRect(0.0f, 0.0f, 320.0f, 240.0f)];
NSData *jpegData = [jpegImageRep representationUsingType:NSJPEGFileType
                                              properties:[NSDictionary dictionaryWithObject:@0.8f forKey:NSImageCompressionFactor]];

[image4 unlockFocus];

[jpegData writeToFile:[NSString stringWithFormat:@"%@/redRectangle-comparison.jpg", desktop]

Be careful about object ownership around NSOperation and NSOperationQueue

For recent years, Apple people concentrated more on iOS than Mac OS X.
So, during that period of time, I’ve noticed that the quality of SDK for OS X and its documentation got worse.

In the case of NSOperation and NSOperationQueue, actually it was announced before the iOS was announced as far as I remember.
However, at that time, they were implemented around pthread or NSThread to provide eaiser pattern for multithreaded programming under specific scenario. ( Although those serial and pipe-like working model is quite convenient in many circumstances, but not always still. If you need more sophisticated interaction among threads, etc, you still need implementation with pthread/NSThread. )

Here is one example.
Were they clear about object ownership for NSOperation ( and its child classes ) when it’s added into a queue?
For tasks like it’s just queued and quickly consumed and gone, it will not easy to catch a case where an instance of a concrete children classes of NSOperation is deallocated while it’s in a queue and being processed.

However, today I did noticed such a case. So, be careful about this thing.
Making a pattern around something looks cool. It may show yourself a very skillful developer. By glancing at that kind of code, people can think of you as such.
However, it’s only skin-deep.

OperationQueue, Operation and ownership

ADDED : According to the document of NSOperationQueue, it says for addOperation:

The operation object to be added to the queue. In memory-managed applications, this object is retained by the operation queue. In garbage-collected applications, the queue strongly references the operation object.

So, at least it’s said to retain the operation. But be careful about it.

allocWithZone: Why doesn’t it matter much nowadays.

From StackOverflow : What is difference between alloc and allocWithZone?

Correct. The reality, though, is that pretty much nothing uses zones. It was originally intended to give the ability to, say, co-locate all of the objects related to a document in a zone and then bulk destroy them by simply deallocating the zone. In practice, this proved unworkable and zones haven’t been used in more than a decade in the OpenStep APIs.

In my case, why I didn’t use allocWithZone: much is because I believe my code should be fast and efficient enough even without memory zone. For special case where we want to make memory allocation/deallocation fast, we can use memory zone, but nowadays ARC takes care of memory allocation. If people are OK with ARC largely, there will be less and less people who care about allocWithZone.

For Windows, my team had used our own special allocation ( malloc/free/new/delete ) functions in C++ to allocate a big chunk of memory and give back memory aligned portions of the allocate space to callers of those new memory allocation/deallocation functions/methods.
For environment which requires really fast operation, it was beneficial.
So, for that.. probably still allocWithZone is useful.. but as said above.. who cares?

Geocoding “Service” for Mac

Oh.. If you need to use “geocode” often, this tip will be quite useful.


%d bloggers like this: