Call: 0123456789 | Email: info@example.com

何以更改Xcode的整顿个版权音皓模板?(How to change entire copyright notice template for Xcode?)


  I’ve found a few answers on how to change your company name, but is there any way to change the entire copyright template in Xcode?

  For example:

  Change :

  (c) 2012 MyCoolCompany

  to :

  (c) 2012 MyCoolCompany, unauthorized reproduction is prohibited, contact bla-bla-bla@example.com for details, etc.

  Go to :

  /Developer/Library/Xcode/Templates/File Templates

  or if you’re using the newer self contained Xcode.app,

  /Applications/Xcode.app/Contents/Developer/Library/Xcode/Templates/File Templates

  To avoid the templates from being clobbered by Xcode updates, make a copy of the template that you want to edit and move it to your home library folder–

  ~/Library/Application Support/Developer/Shared/Xcode/File Templates

  If – let’s say – it’s the Objective-C class template you want to change then, go to the following subdirectory :

  /Cocoa/Objective-C class.xctemplate

  Open :

  NSObject/___FILEBASENAME___.h

  NSObject/___FILEBASENAME___.m

  And edit them.

  Hint : You’ll have to tweak as many template files as you need (e.g. if you need your copyright header to be valid for NSDocument subclasses, then make sure you edit those files too… ;-))

  An example (of what my ___FILEBASENAME___ files look like) :

  本文地址:IT屋 ? How to change entire copyright notice template for Xcode?

  How to change Mac display brightness from cocoa application?

  Have a look here: Alec Jacobson’s Brightness Menu (source is available) and here: Adjust Brightness from the Terminal.

  本文地址:IT屋 ? Programmatically change Mac display brightness

  When implementing an +initialize or +load method in one of your Objective-C classes, should you always start with this kind of guard?:

  @implementation MyClass

  + (void)initialize {

  if (self==[MyClass class]) {

  …

  }

  }

  …

  @end

  Seems like code in +load and +initialize usually only wants to be executed once. So this would help avoid dupe execution when subclasses load/initialize.

  I guess I’m just wanting some reinforcement from some ObjC wizards that this is necessary/common practice…

  What’s the common wisdom on this? would you recommend always doing this?

  Is your advice the same for both +load and +initialize, or is there a difference in they way they should be handled?

  thanks.

  Yes, you should do this in your intialize and load methods if you are initializing globals that should only be initialized once.

  That said, there are a number of cases where you may avoid it…

  You shouldn’t wrap with this conditional if the work needs to be performed on every inheritant of every class:

  There are also situations where you just needn’t bother:

  The “idempotent” part is relevant. An initializer should just be setting the initial state (which should be the same each time). In a good initializer, repetition shouldn’t matter. Although I suppose that if you forget to wrap the method in the conditional when it does matter, this might be annoying.

  edited addition: A different approach, that properly reflects any initialize-only-once requirements would be to test if your properties to initialize are initialized already. i.e.

  id myGlobalObject=nil;

  +(void)initialize

  {

  if (myGlobalObject==nil)

  {

  myGlobalObject=[[MyGlobalClass alloc] init];

  }

  }

  本文地址:IT屋 ? Should +initialize/+load always start with an: if (self==[MyClass class]) guard?

  I have an existing OS X app, and after converting to Storyboards as the main interface, my app delegate is no longer being used. Before, the MainMenu.xib had an “App Delegate” object, and I could set its class to my app delegate. However, the Storyboard contains no such object.

  How do I get my AppDelegate back and keep storyboards? I feel like I’m missing something obvious.

  If you don’t specify it to be a Document-Based Application, Xcode will create an AppDelegate.swift class and connect it up in the Application Scene for you.

  As of right now (Xcode Beta-2), new Document-Based apps don’t come with a stub AppDelegate.swift file. Instead, there’s ViewController.swift and Document.swift. Worse, the Document.swift file incorrectly instantiates the same Main.storyboard for documents.

  Here’s one way I got it to work:

  Here’s a working example of an AppDelegate.swift file for a Document-Based app that also has a separate, single main Application window, and a non-modal Preference window:

  // AppDelegate.swift

  import Cocoa

  class AppDelegate: NSObject, NSApplicationDelegate {

  //init() {

  // super.init()

  // remove this if you don’t use it

  //}

  var application: NSApplication?=nil

  func applicationDidFinishLaunching(notification: NSNotification) {

  application=notification.object as? NSApplication

  let path=NSBundle.mainBundle().pathForResource(“Defaults”, ofType: “plist”)

  let defaults=NSDictionary(contentsOfFile:path)

  NSUserDefaults.standardUserDefaults().registerDefaults(defaults)

  NSUserDefaultsController.sharedUserDefaultsController().initialValues=defaults

  NSUserDefaultsController.sharedUserDefaultsController().appliesImmediately=true

  }

  func applicationDidBecomeActive(notification: NSNotification) {

  if application?.orderedDocuments?.count < 1 { showApplication(self) }

  }

  //func applicationWillFinishLaunching(notification: NSNotification) {

  // remove this if you don’t use it

  //}

  func applicationWillTerminate(notification: NSNotification) {

  NSUserDefaults.standardUserDefaults().synchronize()

  }

  func applicationShouldOpenUntitledFile(app: NSApplication) -> Bool { return false }

  func applicationShouldTerminateAfterLastWindowClosed(app: NSApplication) -> Bool { return false }

  var applicationController: NSWindowController?

  @IBAction func showApplication(sender : AnyObject) {

  if !applicationController {

  let storyboard=NSStoryboard(name: “Application”, bundle: nil)

  applicationController=storyboard.instantiateInitialController() as? NSWindowController

  if let window=applicationController?.window {

  window.titlebarAppearsTransparent=true

  window.titleVisibility=NSWindowTitleVisibility.Hidden

  window.styleMask |=NSFullSizeContentViewWindowMask

  }

  }

  if applicationController { applicationController!.showWindow(sender) }

  }

  var preferencesController: NSWindowController?

  @IBAction func showPreferences(sender : AnyObject) {

  if !preferencesController {

  let storyboard=NSStoryboard(name: “Preferences”, bundle: nil)

  preferencesController=storyboard.instantiateInitialController() as? NSWindowController

  }

  if preferencesController { preferencesController!.showWindow(sender) }

  }

  }

  本文地址:IT屋 ? AppDelegate for Cocoa app using Storyboards in Xcode 6

  How can I pop up Webkit’s Web Inspector from my WebView object programmatically?

  I succeed to enable Webkit’s Web Inspector on my WebView.

  It’s working well, and now I can pop it up by clicking “Inspect Element” on context menu.

  And I want to do this with my push button. But I couldn’t find a proper way to do this.

  My DOM knowledge is 10 years old, very newbie on HTML DOM of nowadays.

  Is there any way to do this?

  I found a class document: InspectorController. I think this is a kind of key. But I cannot know what object exposes and how can I use this.

  Environment:

  There is no public API for interacting with the WebInspector via the DOM or Cocoa. You should file an enhancement request at https://bugreport.apple.com/ asking for this API.

  InspectorController is also an internal implementation detail of the WebInspector and its likely a bug that its on the documentation website.

  本文地址:IT屋 ? How can I pop up Webkit’s Web Inspector from my WebView object programmatically?

  I need to understand how NSView autoresizes it’s views. I’ve set everything up in IB and my subviews resize nicely (when I resize my window around with a mouse). However, if I do [myMainView setFrame:] with my new frame rect, nothing happens. All of my sub-views are still the original size (even though the main view has the correct dimensions). Child’s resizeWithOldSuperviewSize: gets called, but it’s still not appropriately sized.

  I have a screen-full of cocoa elements on screen (screen #1), label, image, video. There’s a well-defined layout for these elements. I’ve setup autoresizing behavior via Interface Builder that works very well. Resizing the main window resizes the elements in a satisfying manner.

  Now, the user clicks the “next” button, whereupon a second screenfull of elements (screen #2) is to be drawn. My layouts are built based on a canonical screensize (say, 800×600). But now the window is larger (or smaller) because it was resized in screen #1. So the elements are now only taking a small area in the window, instead of being appropriately sized to fill the available space. I want to scale these elements.

  Am I misunderstanding how autoresizing works? How can I trigger the autoresize machinery underneath NSView manually?

  There are two things I can do:

  Turns out my approach is correct. I was setting the frame size to an incorrect value, thus I wasn’t getting the expected behavior. Doh.

  本文地址:IT屋 ? NSView’s autoresizing behavior

  I am coming from an iOS background and am new to Mac OSX (coco app) development.

  Starting with apple sample code project “Simple Cocoa App” as a base, I want to be able to switch between different “View Controllers” or even just between NSViews in any manner similar to that of iOS apps.

  Unfortunately, I could not find a way to accomplish this — and the internet is rather lacking in resources tied to keywords like “View switching in cocoa apps, switching views in mac apps, mac app dev tutorials”…

  Do any of you know a tutorial that, and here’s the kicker, actually covers the matter of switching between views? Or perhaps know of any quick way you might be able to explain in your Stack Overflow answer?

  Proof Of Concept

  A very simple proof-of-concept could be the following. In a simple app, there are two views – Screen 1 (currently displayed) and Screen 2 (hidden off screen):

  STEP 1) Start app, Screen 1 appears (contains Label “Screen 1” and Button “Go Next”)

  STEP 2) Press the Button

  STEP 3) Screen 1 slides offscreen as

  STEP 4) Screen 2 slides in (contains a single Label “Screen 2”)

  Thanks.

  Core Animation is not as deeply integrated in OS X as it is on iOS.

  Therefore you will need to do a lot yourself.

  What you could do is use the window’s contentView as a superview and then do the following to switch to another view ( animated ).

  - (void)switchSubViews:(NSView *)newSubview

  {

  NSView *mainView=[[self window] contentView];

  // use a for loop if you want it to run on older OS’s

  [mainView removeAllSubViews];

  // fade out

  [[mainView animator] setAplhaValue:0.0f];

  // make the sub view the same size as our super view

  [newSubView setFrame:[mainView bounds]];

  // *push* our new sub view

  [mainView addSubView:newSubView];

  // fade in

  [[mainView animator] setAlphaValue:1.0f];

  }

  This won’t give you your desired effect however. If you want it to give it a sorta move effect you have to include QuartzCore.framework and do the following:

  - (void)prepareViews

  { // this method will make sure we can animate in the switchSubViewsMethod

  CATransition *transition=[CATransition animation];

  [transition setType:kCATransitionPush];

  [transition setSubtype:kCATransitionFromLeft];

  NSView *mainView=[[self window] contentView];

  [mainView setAnimations:[NSDictionary dictionaryWithObject:transition forKey:@”subviews”]];

  [mainView setWantsLayer:YES];

  }

  then in the switchSubViews: you only have to use:

  [[mainView animator] addSubView:newSubView];

  本文地址:IT屋 ? Easy Switching of “View Controllers” in Mac Apps (similar to iOS)

  I’m planning to do a Cocoa app that requires code syntax to be colored (in all common languages). Instead of writing my own code highlighter/parser, are there any pre-made solutions available?

  Thanks

  You might be able to use something like Geshi, but there’re also the resources listed here: http://www.cocoadev.com/index.pl?SyntaxHighlighting

  Edit

  More links:

  本文地址:IT屋 ? Syntax coloring for Cocoa app

  I’m trying to achieve something like this

  NSMutableArray *myArray=[NSMutableArray arrayWithObjects:@”A”,@”B”,@”C”, nil];

  NSLog(@”Array: %@”, myArray);

  //logs A, B, C.

  //reverse code here

  NSLog(@”Array: %@”, myArray);

  //logs C, B, A

  The code isn’t exact, just a demo. But you get the idea.

  Any way to do this?

  Simply use;

  NSArray* reversed=[[myArray reverseObjectEnumerator] allObjects];

  The order is documented to be correct:

  This array contains all the remaining objects of the enumerator in enumerated order [emphasis added].

  本文地址:IT屋 ? How do I reverse the order of objects in an NSMutableArray?

  Is there any complete documentation (the interface is present in crt_externs.h) about this functions :

  _NSGetArgc and _NSGetArgv

  I can’t get any documentation on the apple website about this functions.

  If all you need to do is get the command line arguments in Cocoa, you can do:

  NSArray *arguments=[[NSProcessInfo processInfo] arguments];

  本文地址:IT屋 ? Accessing command line arguments in Objective-C

  I was migrating a block of code to automatic reference counting (ARC), and had the ARC migrator throw the error

  NSInvocation’s setArgument is not safe to be used with an object with

  ownership other than __unsafe_unretained

  on code where I had allocated an object using something like

  NSDecimalNumber *testNumber1=[[NSDecimalNumber alloc] initWithString:@”1.0″];

  then set it as an NSInvocation argument using

  [theInvocation setArgument:&testNumber1 atIndex:2];

  Why is it preventing you from doing this? It seems just as bad to use __unsafe_unretained objects as arguments. For example, the following code causes a crash under ARC:

  NSDecimalNumber *testNumber1=[[NSDecimalNumber alloc] initWithString:@”1.0″];

  NSMutableArray *testArray=[[NSMutableArray alloc] init];

  __unsafe_unretained NSDecimalNumber *tempNumber=testNumber1;

  NSLog(@”Array count before invocation: %ld”, [testArray count]);

  // [testArray addObject:testNumber1];

  SEL theSelector=@selector(addObject:);

  NSMethodSignature *sig=[testArray methodSignatureForSelector:theSelector];

  NSInvocation *theInvocation=[NSInvocation invocationWithMethodSignature:sig];

  [theInvocation setTarget:testArray];

  [theInvocation setSelector:theSelector];

  [theInvocation setArgument:&tempNumber atIndex:2];

  // [theInvocation retainArguments];

  // Let’s say we don’t use this invocation until after the original pointer is gone

  testNumber1=nil;

  [theInvocation invoke];

  theInvocation=nil;

  NSLog(@”Array count after invocation: %ld”, [testArray count]);

  testArray=nil;

  due to the overrelease of testNumber1, because the temporary __unsafe_unretained tempNumber variable is not holding on to it after the original pointer is set to nil (simulating a case where the invocation is used after the original reference to an argument has gone away). If the -retainArguments line is uncommented (causing the NSInvocation to hold on to the argument), this code does not crash.

  The exact same crash happens if I use testNumber1 directly as an argument to -setArgument:, and it’s also fixed if you use -retainArguments. Why, then, does the ARC migrator say that using a strongly held pointer as an argument to NSInvocation’s -setArgument: is unsafe, unless you use something that is __unsafe_unretained?

  This is a complete guess, but might it be something to do with the argument being passed in by reference as a void*?

  In the case you’ve mentioned, this doesn’t really seem a problem, but if you were to call, eg. getArgument:atIndex: then the compiler wouldn’t have any way of knowing whether the returned argument needed to be retained.

  From NSInvocation.h:

  - (void)getArgument:(void *)argumentLocation atIndex:(NSInteger)idx;

  - (void)setArgument:(void *)argumentLocation atIndex:(NSInteger)idx;

  Given that the compiler doesn’t know whether the method will return by reference or not (these two method declarations have identical types and attributes), perhaps the migrator is being (sensibly) cautious and telling you to avoid void pointers to strong pointers?

  Eg:

  NSDecimalNumber* val;

  [anInvocation getArgument:&val atIndex:2];

  anInvocation=nil;

  NSLog(@”%@”, val); // kaboom!

  __unsafe_unretained NSDecimalNumber* tempVal;

  [anInvocation getArgument:&tempVal atIndex:2];

  NSDecimalNumber* val=tempVal;

  anInvocation=nil;

  NSLog(@”%@”, val); // fine

  本文地址:IT屋 ? Why does the ARC migrator say that NSInvocation’s -setArgument: is not safe unless the argument is __unsafe_unretained?

  I’m looking for a comprehensive list of the available key codes that can be used with Cocoa’s NSEvent class. The NSEvent class has a keyCode property, which is defined as unsigned short. The following code, when placed in an appropriate UI object, will echo the key codes as they are pressed:

  - (void)keyDown:(NSEvent *)theEvent

  {

  NSLog(@”%d”, [theEvent keyCode]);

  }

  From this code, I can easily see which codes match certain keys, but I would like to find an official document somewhere that lists all of them. I expected Apple to have a header file somewhere that looked like this:

  enum {

  …

  NSKeyCodeLeftArrow=123,

  NSKeyCodeRightArrow=124,

  …

  };

  But if there is one, I have yet to find it.

  As far as I know, there is no enum or list of key codes. However, to get similar behavior, you can call interpretKeyEvents: in keyDown: which will call appropriate action methods, all of which are documented in NSResponder (e.g. moveLeft:, insertTab:, etc.)

  本文地址:IT屋 ? Where can I find a list of key codes for use with Cocoa’s NSEvent class?

  I am learning iOS development in Objective-C, and I have found a lot of code examples.

  Some of them, though, say that they are only for Mac OS X (not iOS).

  Can someone please explain to me what is the difference between Cocoa and Cocoa Touch (at a library level), so that I know what code will work and what will not work?

  Thank you.

  Cocoa is commonly referred to as the combination of the Foundation and AppKit frameworks, while Cocoa Touch is the combination of the Foundation and UIKit frameworks.

  Cocoa and Cocoa Touch sit on top of other collections of frameworks to create the API stacks. The other layers are Media, Core Services and Core OS.

  The main difference between Cocoa and Cocoa touch is that the UI classes and APIs aren’t the same as Mac OS X, so instead of NSTextField, you have UITextField. Many of the classes share the same functionality and can be ported quite easily by simply changing the class name, though most will require some more changes, but usually nothing too heavy.

  There are also some differences between the Foundation frameworks in Cocoa and Cocoa Touch, most commonly missing classes, eg, Cocoa has NSHost and Cocoa Touch doesn’t.

  You will come to know more of the nuances between the two and will soon be able to instinctively know what will work on an iPhone with little/no modification and what will require some work to port between, but it’s not that difficult.

  本文地址:IT屋 ? Cocoa versus Cocoa Touch- What is the difference?

  I have a super view, which has 2 subviews.

  These subviews are overlapped.

  Whenever i choose a view from a menu, corresponding view should become the front view and handle actions.

  i.e., it should be the front most subview.

  acceptsFirstResponder resigns all work fine.

  But the mouse down events are sent to the topmost sub view which was set.

  Regards,

  Dhana

  Here’s another way to accomplish this that’s a bit more clear and succinct:

  [viewToBeMadeForemost removeFromSuperview];

  [self addSubview:viewToBeMadeForemost positioned:NSWindowAbove relativeTo:nil];

  Per the documentation for this method, when you use relativeTo:nil the view is added above (or below, with NSWindowBelow) all of its siblings.

  本文地址:IT屋 ? How do I make an NSView move to the front of all NSViews

  For those distributing Mac apps outside the Mac App Store, how are you planning to support updating and sandboxing? I’m guessing most people’s answers for the time being is that they’re not, but I hope that eventually non-MAS apps could be sandboxed just like MAS apps.

  To use Sparkle, your app would need network access, which could be granted, as well as the ability to overwrite itself in Applications. Currently you could do this with the com.apple.security.temporary-exception.files.absolute-path.read-write entitlement, but that’s not a good solution. It will likely go away, and even if it doesn’t there’s little point in sandboxing an app if you’re going to give it full filesystem read-write access as well as network access.

  Has anyone already gone down this path and found a good solution? I ask because I try to keep my MAS build and my non-MAS build as identical as possible, and I’m currently looking at having my MAS build sandboxed and my non-MAS build not.

  In a conversation started by @chockenberry on twitter, @andy_matuschak responded favorably to creating an XPC service for Sparkle.

  I have a pull request open on GitHub that actually creates the XPC service. Hopefully, this will get incorporated into Sparkle soon.

  本文地址:IT屋 ? Can you update a sandboxed Mac app using Sparkle or something similar?

  I am working on an iPhone app, and in a particular view I need to load two different entities: One that will populate a UITableView, and another that will populate a UITextView.

  Is it possible to fetch both properties using a single NSFetchedResultsController?

  Or do I need to use two different NSFetchedResultsControllers?

  Any ideas on how to best approach this problem?

  Each fetch request has only one entity and each fetched results controller has only one fetch. Therefore, you need separate controllers for each entity.

  If you think about it, how would you make a predicate to fetch two logically separate entities?

  You probably don’t need two fetches at all. In most cases, you can fetch the entities that populate the table and then use a relationship for the entity of the selected row to populate something like a text view.

  本文地址:IT屋 ? Core data: can NSFetchedResultsController fetch two different entities?

  I’ve got a background process that makes a transparent window appear when a hotkey is pressed:

  [window makeKeyAndOrderFront:nil];

  [[content animator] setAlphaValue:1.0]; // alpha was 0.0

  … the window shows up fine & in front of the other windows (as I want it to), however until I manually click the window whatever application was active when the window appears remains active. I was expecting the ‘makeKeyAndOrderFront’ to make the application active as well, however adding a NSLog line to my -applicationWillBecomeActive shows it’s not getting any active notification until the mouse click is performed.

  Does anyone know how I can set my application active @ the same time I issue the -makeKeyAndOrderFront ? I need it active so that it can begin accepting keyboard input – any assistance needed 🙂

  Look at [[NSApplication sharedApplication] activateIgnoringOtherApps : YES];.

  本文地址:IT屋 ? How to programmatically make cocoa application active

  How do I save an NSString as a .txt file on my apps local documents directory (UTF-8)?

  NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

  NSString *documentsDirectory=[paths objectAtIndex:0]; // Get documents directory

  NSError *error;

  BOOL succeed=[myString writeToFile:[documentsDirectory stringByAppendingPathComponent:@”myfile.txt”]

  atomically:YES encoding:NSUTF8StringEncoding error:&error];

  if (!succeed){

  // Handle error here

  }

  本文地址:IT屋 ? How do I save an NSString as a .txt file on my apps local documents directory?

  I’m using OCMock to mock some Core Data objects. Previously, I had the properties implemented with Objective-C 1.0 style explicit accessors:

  // — Old Core Data object header

  @interface MyItem : NSManagedObject {}

  - (NSString *) PDFName;

  - (void) setPDFName:(NSString *)pdfName;

  @end

  // — implementation provides generated implementations for both getter and setter

  Now I’ve moved the code to Objective-C 2.0 and want to take advantage of the new @property syntax, and the dynamically-generated method implementations for Core Data objects:

  // — New Core Data object header

  @interface MyItem : NSManagedObject {}

  @property (nonatomic, retain) NSString *PDFName;

  @end

  // — Core Data object implementation

  @implementation MyItem

  @dynamic PDFName;

  @end

  However, now when I create a mock item, it doesn’t seem to handle the dynamic properties:

  // — creating the mock item

  id mockItem=[OCMockObject mockForClass:[MyItem class]];

  [[[mockItem stub] andReturn:@”fakepath.pdf”] PDFName]; // <– throws exception here

  The error looks like this:

  Test Case ‘-[MyItem_Test testMyItem]’ started.

  2009-12-09 11:47:39.044 MyApp[82120:903] NSExceptionHandler has recorded the following exception:

  NSInvalidArgumentException — *** -[NSProxy doesNotRecognizeSelector:PDFName] called!

  Stack trace: 0x916a4d24 0x92115509 0x97879138 0x978790aa 0x9090cb09 0x97820db6 0x97820982 0x10d97ff 0x10d9834 0x9782005d 0x9781ffc8 0x20103d66 0x20103e8c 0x20103642 0x20107024 0x20103642 0x20107024 0x20103642 0x20105bfe 0x907fead9 0x977e4edb 0x977e2864 0x977e2691 0x90877ad9 0xbf565 0xbf154 0x107715 0x1076c3 0x1082e4 0x89d9b 0x8a1e5 0x894eb 0x907e81c7 0x978019a9 0x978013da 0x907dd094 0x907ea471 0x9478c7bd 0x9478c1b9 0x94784535 0x5ede 0x326a 0x5

  Unknown.m:0: error: -[MyItem_Test testMyItem] : *** -[NSProxy doesNotRecognizeSelector:PDFName] called!

  Am doing something wrong? Is there another way to mock a Core Data / object with @dynamic prooperties?

  Also responded to your cross-post on the OCMock Forum

  Check out http://iamleeg.blogspot.com/2009/09/unit-testing-core-data-driven-apps.html.

  Basically he suggests abstracting out your Core Data object’s interface to a protocol, and using that protocol instead of the class where you pass instances of your core data object around.

  I do this for my core data objects. Then you can use mockForProtocol:

  id mockItem=[OCMockObject mockForProtocol:@protocol(MyItemInterface)];

  [[[mockItem expect] andReturn:@”fakepath.pdf”] PDFName];

  Works great! He also suggests creating a non-core data mock implementation of the interface which just synthesizes the properties:

  @implementation MockMyItem

  @synthesize PDFName;

  @end

  …

  id myItemStub=[[MockMyItem alloc] init] autorelease];

  [myItem setPDFName:@”fakepath.pdf”];

  I’ve used this as well, but I’m not sure it adds anything over the mockForProtocol:/stub: approach, and it’s one more thing to maintain.

  本文地址:IT屋 ? OCMock with Core Data dynamic properties problem

  I have get currency code (Eg: USD, EUR, INR) from webservice response. I need to show the currency symbols for the corresponding currency code. If the currency code is USD, i need to show $, if the currency code is EUR i need to show . How can i do this? Please suggest any idea or sample code to do this. Please help me. Thanks in advance.

  This code works charm in my project. I will share this to you all.

  NSString *currencyCode=@”EUR”;

  NSLocale *locale=[[[NSLocale alloc] initWithLocaleIdentifier:currencyCode] autorelease];

  NSString *currencySymbol=[NSString stringWithFormat:@”%@”,[locale displayNameForKey:NSLocaleCurrencySymbol value:currencyCode]];

  NSLog(@”Currency Symbol : %@”, currencySymbol);

  Thanks.

  本文地址:IT屋 ? How can i get currency symbols from currency code in iphone?

  This question is concerning the code from this question: Detect headphone button presses in OS X

  Their answer was marked correct, however I couldn’t get their code to work (this may be because of my lack of knowledge of objective-c). I followed their instructions, and modified three files. This is what I have tried (I have also looked at Apple’s IOKit documentation and could not find any headphone hardware button documentation):

  AwesomeClass.h

  #import

  #include “KeyboardPaneController.h”

  @interface AwesomeClass : KeyboardPaneController

  + (NSArray *) allKeyboards;

  - (void) initKeyboardElements: (NSArray *) elements;

  - (void) ddhidQueueHasEvents: (DDHidQueue *) hidQueue;

  @end

  AwesomeClass.m

  #import “AwesomeClass.h”

  #import “DDHidLib.h”

  @implementation AwesomeClass

  + (NSArray *) allKeyboards;

  {

  NSArray *array=[DDHidDevice allDevicesMatchingUsagePage: kHIDPage_Consumer

  usageId: kHIDUsage_GD_Pointer

  withClass: self

  skipZeroLocations: NO];

  //Only return “Apple Mikey HID Driver”, if not found, return nil.

  for (DDHidDevice *device in array) {

  if ([[device productName] isEqualToString:@”Apple Mikey HID Driver”]) {

  return [NSArray arrayWithObject:device];

  }

  }

  return nil;

  }

  - (void) initKeyboardElements: (NSArray *) elements;

  {

  NSEnumerator * e=[elements objectEnumerator];

  DDHidElement * element;

  while (element=[e nextObject])

  {

  unsigned usagePage=[[element usage] usagePage];

  unsigned usageId=[[element usage] usageId];

  if (usagePage==kHIDPage_GenericDesktop)

  {

  if ((usageId >=0x89) && (usageId <=0x8D))

  {

  [mKeyElements addObject: element];

  }

  }

  NSArray * subElements=[element elements];

  if (subElements !=nil)

  [self initKeyboardElements: subElements];

  }

  }

  - (void) ddhidQueueHasEvents: (DDHidQueue *) hidQueue;

  {

  DDHidEvent * event;

  while ((event=[hidQueue nextEvent]))

  {

  DDHidElement * element=[self elementForCookie: [event elementCookie]];

  unsigned usageId=[[element usage] usageId];

  SInt32 value=[event value];

  if (value==1)

  [self ddhidKeyboard: self keyDown: usageId];

  }

  }

  @end

  …as well as modifying one line in KeyboardPaneController.m (that was shown in the instructions). Due to the lack of documentation on the framework, it’s really difficult to find an answer (the poster has been offline for more than a year, so I’m assuming I probably won’t get a response back). The code was tested on lion, and I have mountain lion so that might be the issue.

  I know that this is definitely possible to implement because iTunes is very responsive to my headphone-button-presses (which is a bit of a nuance). I’d like to be able to control Spotify with the buttons on my headphones, rather than iTunes.

  A test shows it isn’t implemented as a keyboard anymore:

  id array=[[DDHidDevice allDevices] filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@”productName==”Apple Mikey HID Driver””]];

  DDHidDevice *mic=[array count] ? [array objectAtIndex:0] : nil;

  // it isn’t a keyboard

  NSLog(@”%@”, mic.primaryUsage);

  assert(mic.usage==1 && mic.usagePage==12);

  You can’t treat it like a HIDKeyboard either (tried, it doesn’t send key presses), nor a HIDMouse or HID Joystick.

  I dug into the HIDQueue class and checked if the mikey fires any low level events and it does fire low level events! The queueCallbackFunction is called for presses (if you don’t filter the queue for specific events. To filter it, see initWithKeyboardEvents in DDHidKeyboard.

  Now all you have to do is map the low level events to the correct buttons and you are done. Maybe wrap it all in a nice class too. Here’s a sample of the class and relevant code on GitHub.

  本文地址:IT屋 ? Detect hardware headphone presses in mac

  I want to define one protocol with few properties and need to use those properties in another NSObject subclass. Please give me link or example code. I need that to work with 10.5.

  Thanks

  PLEASE CHECK THE FOLLOWING SAMPLE CODE

  @protocol MyProtocol

  @property (nonatomic, readonly) id someObject;

  @property (nonatomic, getter=isAlive) BOOL alive;

  @end

  #import “MyProtocol.h”

  @interface MyCustomClass : NSObject {

  }

  @end

  #import “MyCustomClass.h”

  @implementation MyCustomClass

  @synthesize someObject,alive;

  @end

  **Added:

  Compling code with x86_64 architecture works fine. But error if i’ll change the architecture to i386, then i am getting following warnings:

  MyCustomClass.m:13: error: synthesized property ‘someObject’ must either be named the same as a compatible ivar or must explicitly name an ivar

  error: synthesized property ‘alive’ must either be named the same as a compatible ivar or must explicitly name an ivar

  I just want to know why it is working in x86_64 with @synthesize and not in i386.**

  @property just says to the compiler that the class is expected to define the methods to match that property.

  @protocol MyProtocol

  @property (nonatomic, readonly) id someObject;

  @property (nonatomic, getter=isAlive) BOOL alive;

  @end

  Anything implementing that protocol will now need to have

  - (id)someObject;

  - (BOOL)isAlive;

  - (void)setAlive:(BOOL)aBOOL;

  本文地址:IT屋 ? How to define and implement properties in protocol

  There are several terminal commands to retrieve the numerical / abbreviated Model Identifier for Mac hardware.

  These dump a string with the hardware name and x,y versioning. Currently we have to maintain a table to convert these identifiers into the full english machine description.

  Is there an API, or better a command line tool that can produce the more human friendly names that match Apple’s documentation MacBook Pro 15-inch, Mid 2009 instead of the more abbreviated MacBookPro5,3 Model Identifier?enter image description here

  Quite simply, how does System Profiler get the nice full names of Macs and can I exploit that information systematically via script or program?

  Did check the network traffic. System Information is connecting to

  http://support-sp.apple.com

  A full query looks like:

  http://support-sp.apple.com/sp/product?cc=DJWR&lang=de_DE

  Where ‘DJWR’ are the last four characters of the serial number

  More info here: http://blog.coriolis.ch/get-your-apple-device-model-name-in-a-readable-format/

  本文地址:IT屋 ? How does System Profiler retrieve the full Mac hardware identifier?

  I’m trying to add a menu item next to the “copy”, “paste” items in a UITextView. I’ve created a subclass of UITextView and copied the example from apple’s docs here:

  http://developer.apple.com/iphone/library/documentation/General/Conceptual/iPadProgrammingGuide/Text/Text.html#//apple_ref/doc/uid/TP40009370-CH8-SW28

  I simply created a UiTextView in IB and set its class to my CustomTextView class. Unfortunately this didn’t work. Although, if I set my CustomTextView to a subclass of UIView, it works great. Any help here?

  I’ve also made a very simple example project of my situation here:

  apps.popsweet.com/TextViewTrial.zip

  So I ended up using the following with results that I wanted, I placed the following block in the viewDidLoad method of my view controller as Alex hinted to:

  - (void)viewDidLoad {

  [super viewDidLoad];

  UIMenuItem *menuItem=[[UIMenuItem alloc] initWithTitle:@”Change Color” action:@selector(changeColor:)];

  [[UIMenuController sharedMenuController] setMenuItems:[NSArray arrayWithObject:menuItem]];

  [menuItem release];

  }

  Then I added the following to the view controller to show the item conditionally when text is selected within the UITextView which I named “textView”:

  - (BOOL)canPerformAction:(SEL)action withSender:(id)sender {

  if (action==@selector(changeColor:)) {

  if (textView.selectedRange.length > 0) {

  return YES;

  }

  }

  return NO;

  }

  I chose to place the canPerformAction:withSender: method in the view controller instead of a custom UITextView class because this way the other options (e.g. copy, cut, paste, etc.) behave as they normally would since the method is called on every object up the responder chain.

  本文地址:IT屋 ? How do I add a custom UIMenuItem to the UIMenuController in a UITextView?

  I have this consumer class that takes an NSInputStream as argument which will be processed async, and I want to push data that comes from a producer class that requires that it has an NSOutputStream provided as its output source. Now how could I set up a buffering (or transparent) stream that acts as the output stream for the producer, and at the same time as the NSInputStream for my consumer class?

  I’ve looked a bit at the NSOutputStream +outputStreamToMemory and +outputStreamToBuffer:capacity: but haven’t really figured out how to use it as input for an NSInputSource.

  I had some idea of setting up a middle-man class that holds the actual buffer, then creating two subclasses (one for each NSInput/OutputStream) which holds a reference to this buffering class, and having these subclasses delegate most calls to that class, e.g output subclass methods hasSpaceAvailable, write:maxLength:, and for the input, hasBytesAvailable, read:maxLength: etc.

  Any tips on how to approach this situation are appreciated. Thanks.

  One way to accomplish this would be to use the example code on the apple developer site.

  SimpleURLConnection example

  This is how to do it, as can be seen in the PostController.m code

  @interface NSStream (BoundPairAdditions)

  + (void)createBoundInputStream:(NSInputStream **)inputStreamPtr outputStream:(NSOutputStream **)outputStreamPtr bufferSize:(NSUInteger)bufferSize;

  @end

  @implementation NSStream (BoundPairAdditions)

  + (void)createBoundInputStream:(NSInputStream **)inputStreamPtr outputStream:(NSOutputStream **)outputStreamPtr bufferSize:(NSUInteger)bufferSize

  {

  CFReadStreamRef readStream;

  CFWriteStreamRef writeStream;

  assert( (inputStreamPtr !=NULL) || (outputStreamPtr !=NULL) );

  readStream=NULL;

  writeStream=NULL;

  CFStreamCreateBoundPair(

  NULL,

  ((inputStreamPtr !=nil) ? &readStream : NULL),

  ((outputStreamPtr !=nil) ? &writeStream : NULL),

  (CFIndex) bufferSize);

  if (inputStreamPtr !=NULL) {

  *inputStreamPtr=[NSMakeCollectable(readStream) autorelease];

  }

  if (outputStreamPtr !=NULL) {

  *outputStreamPtr=[NSMakeCollectable(writeStream) autorelease];

  }

  }

  @end

  Basically you attach the ends of two streams together with a buffer.

  本文地址:IT屋 ? Buffering NSOutputStream used as NSInputStream?

  I am fairly new to OS X Cocoa programming but have decided to give it a go with the new Swift language.

  I have an NSTableView with 1500 rows (will be more) and 7 columns. There is one checkbox column and the rest are text fields, one with a date formate and one a currency formatter. I first set this up as cell based. Scrolling was buttery smooth (I even did a test adding 1 million rows, still smooth). This was under mavericks.

  I then upgraded to Yosemite, scrolling performance significantly degraded. Enabling Core animation layer checkbox on the table view improved this but was still worse than in mavericks.

  During my reading trying to improve scroll performance in Yosemite I came across “View-Based” NSTableViews. From the documentation it said cell based table views should generally not be used and are only supported for legacy projects.

  I therefore converted my table to a View based table view. Sample simple concept, nothing complicated. The scrolling performance is absolutely terrible. If you scroll very slow it is smooth enough but as soon as you start to scroll faster its like it hasn’t buffered enough and it starts stuttering and jerking. Also when the NSTableview is populated, focusing and defocusing the window takes a second or more (I tried it in mavericks again and this was not present, scrolling was also a little better, but still nowhere near cell based).

  Are view based NSTableviews always bad for scrolling performance? If so why do apple recommend using them over cell based NSTableviews.

  Also some applications like safari and Reeder2 have buttery smooth scrolling even in Yosemite. How do they achieve this?

  Am I missing something or is the performance of OS X just going to hell with each new thing? I.e

  Mavericks > Yosemite

  Cell-Based > View-Based

  Old > New

  Any help is much appreciated. Thanks!

  According to Apple, OSX never enable QuartzCore by default (as iOS, instead, do). So, you need to:

  Quoting Apple docs:

  In iOS apps, Core Animation is always enabled and every view is backed

  by a layer. In OS X, apps must explicitly enable Core Animation

  support by doing the following:

  Link against the QuartzCore framework. (iOS apps must link against

  this framework only if they use Core Animation interfaces explicitly.)

  Enable layer support for one or more of your NSView objects by doing

  one of the following:

  In your nib files, use the View Effects inspector to enable layer

  support for your views. The inspector displays checkboxes for the

  selected view and its subviews. It is recommended that you enable

  layer support in the content view of your window whenever possible.

  For views you create programmatically, call the view’s setWantsLayer:

  method and pass a value of YES to indicate that the view should use

  layers. Enabling layer support in one of the preceding ways creates a

  layer-backed view. With a layer-backed view, the system takes

  responsibility for creating the underlying layer object and for

  keeping that layer updated. In OS X, it is also possible to create a

  layer-hosting view, whereby your app actually creates and manages the

  underlying layer object. (You cannot create layer-hosting views in

  iOS.) For more information on how to create a layer-hosting view, see

  “Layer Hosting Lets You Change the Layer Object in OS X.”

  More on: https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/CoreAnimation_guide/SettingUpLayerObjects/SettingUpLayerObjects.html

  本文地址:IT屋 ? NSTableview View Based Scrolling Performance

  I have a little app that downloads stock prices and was working perfectly (for years) until my recent upgrade to 10.5.7. After the upgrade, the program would crash on this call:

  NSString *currinfo=[NSString stringWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:@”http://finance.yahoo.com/d/quotes.csv?s=%@&f=l1c1p2″, escsymbol]]];

  Oddly, the crash doesn’t happen right away. This line of code is called many times, with no problems, and then the program eventually fails after 1-2 hours due to a crash on this call.

  I originally had a long post here describing my attempts to investigate this problem. I received two suggestions: (i) make the call asynchronous (probably better anyway) and (ii) use NSZombieEnabled to investigate the possibility that an Objective-C object is getting deallocated early (this comment was made in response to stack traces showing failure in objc_msgSend).

  I spent a good deal of time making the call asynchronous (using [[NSURLConnection alloc] initWithRequest:theRequest delegate:self]) and this didn’t help. The program still failed eventually, usually after 10-15 minutes. During this interval before failure, many asynchronous calls were made without any problem, data was returned, etc. Everything was fine. Then the program crashed suddenly again.

  I then turned on NSZombieEnabled. Sure enough, when the program eventually crashed I got the message:

  -[CFArray count]: message sent to deallocated instance 0x16b90bd0

  ”info malloc 0x16b90bd0″ then yielded:

  0: 0x93db810c in malloc_zone_malloc

  1: 0x946bc3d1 in _CFRuntimeCreateInstance

  2: 0x9464a138 in __CFArrayInit

  3: 0x946cd647 in _CFStreamScheduleWithRunLoop

  4: 0x932d1267 in _Z16_scheduleRStreamPKvPv

  5: 0x946bf15c in CFSetApplyFunction

  6: 0x932b0e2b in CFNSchedulingSetScheduleReadStream

  7: 0x9331a310 in _ZN12HTTPProtocol19createAndOpenStreamEv

  8: 0x9332e877 in _ZN19URLConnectionLoader24loaderScheduleOriginLoadEPK13_CFURLRequest

  9: 0x9332d739 in _ZN19URLConnectionLoader26LoaderConnectionEventQueue33processAllEventsAndConsumePayloadEP20XConnectionEventInfoI12XLoaderEvent18XLoaderEventParamsEl

  10: 0x9332dbdd in _ZN19URLConnectionLoader13processEventsEv

  11: 0x932d8dbf in _ZN17MultiplexerSource7performEv

  12: 0x946ba595 in CFRunLoopRunSpecific

  13: 0x946bac78 in CFRunLoopRunInMode

  14: 0x9058c530 in +[NSURLConnection(NSURLConnectionReallyInternal) _resourceLoadLoop:]

  15: 0x90528e0d in -[NSThread main]

  16: 0x905289b4 in __NSThread__main__

  17: 0x93de8155 in _pthread_start

  18: 0x93de8012 in thread_start

  I am no expert in reading stack traces, but doesn’t this trace indicate a problem in Apple code, rather than my code? Or could I somehow be responsible for de-allocation of the CFArray in question? Is there any way for me to further investigate the cause of the problem?

  (Here’s the rest of my original post)

  Seeing that stringWithContentsOfURL is deprecated, I switched to this code:

  pathURL=[NSURL URLWithString:[NSString stringWithFormat:@”http://finance.yahoo.com/d/quotes.csv?s=%@&f=l1c1p2″, escsymbol]];

  NSURLRequest *request=[NSURLRequest requestWithURL:pathURL cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:30.0];

  responseData=[ NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

  NSString *currinfo=nil;

  if ([error code]) { dNSLog((@”%@ %d %@ %@ %@”, [ error domain], [ error code], [ error localizedDescription], request, @”file://localhost/etc/gettytab”)); }

  This didn’t help. The program still crashes on the sendSynchronousRequest line after an arbitrary length of time, with this information in the debugger:

  0 0x93db7286 in mach_msg_trap

  1 0x93dbea7c in mach_msg

  2 0x946ba04e in CFRunLoopRunSpecific

  3 0x946bac78 in CFRunLoopRunInMode

  4 0x932b53eb in CFURLConnectionSendSynchronousRequest

  5 0x905dca4b in +[NSURLConnection sendSynchronousRequest:returningResponse:error:]

  …etc.

  The real crash might actually be in a different thread:

  0 libobjc.A.dylib 0x965c3688 objc_msgSend + 24

  1 com.apple.CoreFoundation 0x946cc581 _CFStreamSignalEventSynch + 193

  2 com.apple.CoreFoundation 0x946ba595 CFRunLoopRunSpecific + 3141

  3 com.apple.CoreFoundation 0x946bac78 CFRunLoopRunInMode + 88

  4 com.apple.Foundation 0x9058c530 +[NSURLConnection(NSURLConnectionReallyInternal) _resourceLoadLoop:] + 320

  5 com.apple.Foundation 0x90528e0d -[NSThread main] + 45

  6 com.apple.Foundation 0x905289b4 __NSThread__main__ + 308

  7 libSystem.B.dylib 0x93de8155 _pthread_start + 321

  8 libSystem.B.dylib 0x93de8012 thread_start + 34

  which I presume is the thread spawned to download the URL. By the way, the error handling code works fine–when I intentionally cause an error by disconnecting from the internet, the error is just reported in the console and the program doesn’t crash.

  This is incredibly frustrating. I would be very happy to spend as much time as necessary tracking down the problem, but I’m kind of at the limits of my knowledge with gdb and especially with assembly language. I don’t know how to find out what is the actual problem for the Foundation code. At first I thought that maybe the autoreleased NSString escsymbol is somehow being deallocated, but sending it a retain message didn’t help. If this were the case, how could I prove it?

  Is anybody else having this problem?

  I think Eugene’s reply in this thread is properly describing the problem; after some testing, here is what I’ve concluded seems to be going on, with hopefully some details to help others stuck with this issue:

  Redirecting URLs will periodically cause failures. This happens both in the sync and async usages of NSURLConnection. I’ve created a test project to track down this bug, and this crash will consistently occur (typically between 25-500 iterations). Running the same test on 10.5.6 or without redirecting URLs does not fail (have run it up to 20,000 iterations).

  There are two possible work-arounds:

  - (NSURLRequest *)connection:(NSURLConnection *)connection

  willSendRequest:(NSURLRequest *)request

  redirectResponse:(NSURLResponse *) redirectResponse

  {

  return request;

  }

  All of this seems to suggest to me that there is something broken in Apple’s implementation in 10.5.7, but if anyone else has any insights as to what might be going on, please chime in.

  I have submitted a bug with my test project to Apple as rdar://6936109 and referenced tjw’s report (Radar 6932684).

  本文地址:IT屋 ? NSURLConnection crashing under 10.5.7

  Is there a way to make my app respond to the play/pause button on Mac?

  EDIT:

  Using the suggested code,I get this console message:

  Could not connect the action buttonPressed: to target of class NSApplication

  Why would that be?

  I accomplished this in my own application by subclassing NSApplication (and setting the app’s principal class to this subclass). It catches seek and play/pause keys and translates them to specific actions in my app delegate.

  Relevant lines:

  #import

  - (void)sendEvent:(NSEvent *)event

  {

  // Catch media key events

  if ([event type]==NSSystemDefined && [event subtype]==8)

  {

  int keyCode=(([event data1] & 0xFFFF0000) >> 16);

  int keyFlags=([event data1] & 0x0000FFFF);

  int keyState=(((keyFlags & 0xFF00) >> 8))==0xA;

  // Process the media key event and return

  [self mediaKeyEvent:keyCode state:keyState];

  return;

  }

  // Continue on to super

  [super sendEvent:event];

  }

  - (void)mediaKeyEvent:(int)key state:(BOOL)state

  {

  switch (key)

  {

  // Play pressed

  case NX_KEYTYPE_PLAY:

  if (state==NO)

  [(TSAppController *)[self delegate] togglePlayPause:self];

  break;

  // Rewind

  case NX_KEYTYPE_FAST:

  if (state==YES)

  [(TSAppController *)[self delegate] seekForward:self];

  break;

  // Previous

  case NX_KEYTYPE_REWIND:

  if (state==YES)

  [(TSAppController *)[self delegate] seekBack:self];

  break;

  }

  }

  本文地址:IT屋 ? Make my Cocoa app respond to the keyboard play/pause key?

  I’m following this tutorial: http://blog.bignerdranch.com/754-scenekit-in-mountain-lion/

  I’m interested in using Scene Kit, but my scenes might potentially have thousands of spheres. To stress-test Scene Kit I tried this:

  SCNSphere *sphere=[SCNSphere sphereWithRadius:0.5];

  for (int i=0; i<10; i++) {

  for(int j=0; j<10; j++){

  for(int k=0; k<10; k++){

  SCNNode *myNode=[SCNNode nodeWithGeometry:sphere];

  myNode.position=SCNVector3Make(i,j,k);

  [root addChildNode:myNode];

  }

  }

  }

  This works fine for, say, 1000 spheres (10^3) but fails (perhaps unsurprisingly) for 1,000,000 spheres (100^3). I don’t mind not being able to use a million spheres, but I’d like to work out what the sensible upper bound is (5,000? 15,000?) and how to increase it.

  What can I do to mitigate this? e.g. I’ve tried sphere.segmentCount=3 and while that speeds up rendering, it doesn’t have much effect on memory usage, which I suspect is the limiting factor.

  Also, there doesn’t seem to be a SCNPoint class. I was thinking about switching to just displaying a point when the number of spheres is too high, but I can’t see from the SceneKit documentation how to display a simple point — the simplest I can see is a triangle.

  Any help is much appreciated.

  Edit: @toyos suggested that the SCNSphere objects are merged into single SCNGeometry object (provided they don’t need to be independently animated, which they don’t), but I can’t find an easy way to do this.

  SCNGeometry is created by using [SCNGeometry geometryWithSources:(* NSArray)sources geometryWithElements:(* NSArray) elements] as documented here, but I’m not clear as to how to create an SCNGeometry object from my spheres.

  e.g. for a single sphere, I could see using sphere.geometryElementCount to get the number of elements and then using that to populate an array using [sphere geometryElementAtIndex:(NSInteger)elementIndex] which would give me the elements, but I’m not sure how to get the “sources” (or what they even are). The method to get the geometry sources is [sphere geometrySourcesForSemantic:(NSString*) semantic], but what is this semantic string? (is it meant to be “normals” or “vertices” or is this something else? the documentation quite helpfully says the semantic is “The semantic value of the geometry source.” without saying what possible values of the semantic are)

  That’s just for a single sphere, which would be fairly pointless (since SCNSphere is just a subclass of SCNGeometry anyway), so now I have to add multiple spheres. So would I have to manually translate the vertices of the sphere when adding them to my SCNGeometry object?

  I’m just trying to figure out the most sensible way to do this.

  The semantic strings are SCNGeometrySourceSemanticVertex|Normal|Texcoord …

  For multiple spheres the answer is yes, you have to transform the vertex/normals with the current node transform before flattening.

  Below is a simplified example (i.e it only supports merging the childs of “input” if they all have the same geometry)

  - (SCNNode *) flattenNodeHierarchy:(SCNNode *) input

  {

  SCNNode *result=[SCNNode node];

  NSUInteger nodeCount=[[input childNodes] count];

  if(nodeCount > 0){

  SCNNode *node=[[input childNodes] objectAtIndex:0];

  NSArray *vertexArray=[node.geometry geometrySourcesForSemantic:SCNGeometrySourceSemanticVertex];

  SCNGeometrySource *vertex=[vertexArray objectAtIndex:0];

  SCNGeometryElement *element=[node.geometry geometryElementAtIndex:0]; //todo: support multiple elements

  NSUInteger primitiveCount=element.primitiveCount;

  NSUInteger newPrimitiveCount=primitiveCount * nodeCount;

  size_t elementBufferLength=newPrimitiveCount * 3 * sizeof(int); //nTriangle x 3 vertex * size of int

  int* elementBuffer=(int*)malloc(elementBufferLength);

  NSUInteger vertexCount=[vertex vectorCount];

  NSUInteger newVertexCount=vertexCount * nodeCount;

  SCNVector3 *newVertex=malloc(sizeof(SCNVector3) * newVertexCount);

  SCNVector3 *newNormal=malloc(sizeof(SCNVector3) * newVertexCount); //assume same number of normal/vertex

  //fill

  NSUInteger vertexFillIndex=0;

  NSUInteger primitiveFillIndex=0;

  for(NSUInteger index=0; index< nodeCount; index++){

  NSAutoreleasePool *pool=[[NSAutoreleasePool alloc] init];

  node=[[input childNodes] objectAtIndex:index];

  NSArray *vertexArray=[node.geometry geometrySourcesForSemantic:SCNGeometrySourceSemanticVertex];

  NSArray *normalArray=[node.geometry geometrySourcesForSemantic:SCNGeometrySourceSemanticNormal];

  SCNGeometrySource *vertex=[vertexArray objectAtIndex:0];

  SCNGeometrySource *normals=[normalArray objectAtIndex:0];

  if([vertex bytesPerComponent] !=sizeof(float)){

  NSLog(@”todo: support other byte per component”);

  continue;

  }

  float *vertexBuffer=(float *)[[vertex data] bytes];

  float *normalBuffer=(float *)[[normals data] bytes];

  CATransform3D t=[node transform];

  GLKMatrix4 matrix=MyGLKMatrix4FromCATransform3D(t);

  //append source

  for(NSUInteger vIndex=0; vIndex < vertexCount; vIndex++, vertexFillIndex++){

  GLKVector3 v=GLKVector3Make(vertexBuffer[vIndex * 3], vertexBuffer[vIndex * 3+1], vertexBuffer[vIndex * 3 + 2]);

  GLKVector3 n=GLKVector3Make(normalBuffer[vIndex * 3], normalBuffer[vIndex * 3+1], normalBuffer[vIndex * 3 + 2]);

  //transform

  v=GLKMatrix4MultiplyVector3WithTranslation(matrix, v);

  n=GLKMatrix4MultiplyVector3(matrix, n);

  newVertex[vertexFillIndex]=SCNVector3Make(v.x, v.y, v.z);

  newNormal[vertexFillIndex]=SCNVector3Make(n.x, n.y, n.z);

  }

  //append elements

  //here we assume that all elements are SCNGeometryPrimitiveTypeTriangles

  SCNGeometryElement *element=[node.geometry geometryElementAtIndex:0];

  const void *inputPrimitive=[element.data bytes];

  size_t bpi=element.bytesPerIndex;

  NSUInteger offset=index * vertexCount;

  for(NSUInteger pIndex=0; pIndex < primitiveCount; pIndex++, primitiveFillIndex+=3){

  elementBuffer[primitiveFillIndex]=offset + _getIndex(inputPrimitive, bpi, pIndex*3);

  elementBuffer[primitiveFillIndex+1]=offset + _getIndex(inputPrimitive, bpi, pIndex*3+1);

  elementBuffer[primitiveFillIndex+2]=offset + _getIndex(inputPrimitive, bpi, pIndex*3+2);

  }

  [pool drain];

  }

  NSArray *sources=@[[SCNGeometrySource geometrySourceWithVertices:newVertex count:newVertexCount],

  [SCNGeometrySource geometrySourceWithNormals:newNormal count:newVertexCount]];

  NSData *newElementData=[NSMutableData dataWithBytesNoCopy:elementBuffer length:elementBufferLength freeWhenDone:YES];

  NSArray *elements=@[[SCNGeometryElement geometryElementWithData:newElementData

  primitiveType:SCNGeometryPrimitiveTypeTriangles

  primitiveCount:newPrimitiveCount bytesPerIndex:sizeof(int)]];

  result.geometry=[SCNGeometry geometryWithSources:sources elements:elements];

  //cleanup

  free(newVertex);

  free(newNormal);

  }

  return result;

  }

  //helpers:

  GLKMatrix4 MyGLKMatrix4FromCATransform3D(CATransform3D transform) {

  GLKMatrix4 m={{transform.m11, transform.m12, transform.m13, transform.m14,

  transform.m21, transform.m22, transform.m23, transform.m24,

  transform.m31, transform.m32, transform.m33, transform.m34,

  transform.m41, transform.m42, transform.m43, transform.m44}};

  return m;

  }

  GLKVector3 MySCNVector3ToGLKVector3(SCNVector3 vector) {

  GLKVector3 v={{vector.x, vector.y, vector.z}};

  return v;

  }

  本文地址:IT屋 ? SceneKit on OS X with thousands of objects

  I found out how to create a window in Cocoa programmatically but can’t figure out how to react to events. The window is not reacting to a Quit request or button click.

  I tried adding the following controller and used setDelegate/setTarget without luck:

  @interface AppController : NSObject {

  }

  - (IBAction)doSomething:(id)sender;

  @end

  @implementation AppController

  - (IBAction)doSomething:(id)sender;

  {

  printf(“Button clicked!\n”);

  }

  @end

  int main(int argc, char **args){

  NSRect frame=NSMakeRect(0, 0, 200, 200);

  AppController *controller=[[AppController alloc] init];

  > [[NSApplication sharedApplication] setDelegate:controller];

  NSWindow* window=[[NSWindow alloc] initWithContentRect:frame

  styleMask:NSBorderlessWindowMask|NSClosableWindowMask|NSMiniaturizableWindowMask|NSResizableWindowMask

  backing:NSBackingStoreBuffered

  defer:NO];

  [window setBackgroundColor:[NSColor blueColor]];

  NSButton *button=[ [ NSButton alloc ] initWithFrame: NSMakeRect( 30.0, 20.0, 80.0, 50.0 ) ];

  [ button setBezelStyle:NSRoundedBezelStyle];

  [ button setTitle: @”Click” ];

  > [ button setAction:@selector(doSomething:)];

  > [ button setTarget:controller];

  [ [ window contentView ] addSubview: button ];

  [window makeKeyAndOrderFront:NSApp];

  [[NSRunLoop currentRunLoop] run];

  return 0;

  }

  You need to invoke -[NSApplication run] instead of -[[NSRunLoop currentRunLoop] run]. The reason should be clear if you look at the basic structure of the method:

  - (void)run

  {

  NSAutoreleasePool *pool=[[NSAutoreleasePool alloc] init];

  [self finishLaunching];

  shouldKeepRunning=YES;

  do

  {

  [pool release];

  pool=[[NSAutoreleasePool alloc] init];

  NSEvent *event= [self

  nextEventMatchingMask:NSAnyEventMask

  untilDate:[NSDate distantFuture]

  inMode:NSDefaultRunLoopMode

  dequeue:YES];

  [self sendEvent:event];

  [self updateWindows];

  } while (shouldKeepRunning);

  [pool release];

  }

  NSApplication encapsulates a lot about how to get an event, how to dispatch them and how to update windows.

  本文地址:IT屋 ? How can I create a GUI and react to Cocoa events programmatically?

  Consider the following common situation:

  You have some MainView in your Cocoa application, loaded from a NIB, which is controlled by a MainViewController. Your MainView contains some controls, such as a UILabel infoLabel. You also have a delegate MyDelegate class which receives some sort of event.

  You would like to make sure that when MyDelegate receives its event, the infoLabel is updated appropriately. However, the problem is that MyDelegate does not have a reference to the MainView or the MainViewController and does not know about the label.

  One solution is to pass a MainViewController reference to the delegate object, but this feels wrong because you might find yourself in the undesirable situation where the object has each other’s references.

  What is the proper design to solve this problem?

  In an unnamed developer forum, someone writes:

  So, to make a long story short, I have decided that I will start making use of NSNotifications. The Stanford course online that people have been following is taught by two Apple engineers. They have just now unequivocally said NOT to use the app delegate or global variables, and have said to use NSNotifications, delegates, and K-V observing.

  If that is what the Apple engineers say, I am going to move in that direction.

  The NSNotifications are pretty ingenious in that they don’t really interfere with encapsulation that much. The listener only listens for the notification and an object – I don’t think it has to know or care who sent it.

  So in your example I would consider having the delegate post a notification that the label had changed, or better yet have the controller observe that property if possible.

  本文地址:IT屋 ? Objective-C/Cocoa: Proper design for delegates and controllers

  I’ve no idea why, but on occasion I’ve managed to fix some compile errors, most notably

  error expected specifier-qualifier-list before ‘someClass’

  by moving #import “someClass.h” from the .h file into the .m file. This has also worked with a couple of other problems i’ve encountered that have been (mysteriously from my point of view) related to headers.

  Some cursory googling has turned up the answer “never import headers in header file” and that’s where the advice stops.

  Either I’ve completely made this up, or I’ve picked up the habit from somewhere, but I thought the header was where headers were meant to be imported. Clearly not, but can anyone explain to me why that is, and what’s the preferred way of importing headers?

  Unless you’re inheriting from the class that you’re including, you shouldn’t include headers in headers. If you need to include an object as an interface variable, you should use the @class directive instead; that’ll tell the compiler that the identifier refers to a class.

  Instead, import headers only in implementation files. The compiler will know that your instance variables are pointers to objects, but it doesn’t know the details of the object when parsing the header. All it needs to know is that it’s a class. The compiler can then see the methods of the class when parsing your implementation file; at that point, it does need the class, to verify that it responds to the messages you’re sending.

  Update: I was going to update my answer to respond to some later questions, but Rob Napier has a good follow-up.

  本文地址:IT屋 ? Cocoa: What’s the difference between importing in the header and importing in the main file?

  I am currently looking into solving the problem with the inability to quickly create new files in the Finder. I will open source what I write because I think the Mac community needs this solved.

  On Windows, you can right-click, create new text file.

  OS X, you should be able to do this with a service which would work like this:

  Writing a Finder Service in Snow Leopard is theoretically the way to accomplish this, although I haven’t been able to find any sample code. (I’ll admit I’ve only looked at the documentation very briefly).

  I’m not sure how to get started, whether Apple provide a Services template in Xcode. Basically I’m looking for help with getting a working services project running. The implementation code should then be rather trivial for me to write in Obj-C. So what can I do to create a new working Services project? If i’m wrong about this then tell me the right way to do this and please provide sample code or some steps to get me started.

  Edit: Trust me guys, I’m not an OS X noob. Have tried many apps to achieve work arounds: PathFinder, Automator, Terminal,etc and I’m happy with none of them.

  I want to create a right-clickable menu item for creating New files, the same as Windows has. If this API doesn’t let me do this, then I will modify system files if necessary. But I would rather do it in such a way that doesn’t require me hack OS X.

  The sad fact is that Apple disabled 3rd party contextual menu items when Snow Leopard was released and devs weren’t happy. You could create services under the contextual menu with Automator, but it was very limited.

  Yes, Quicksilver is the way I create files at the moment, unless I’m in the terminal when I touch ~/Desktop/file.txt or wherever.

  If you cannot answer my question by providing source code for an Xcode project for writing a Service, please keep your opinions on how I should be using my computer to yourself. At any rate, I think I will probably be answering my own question after I go and implement this myself.

  Read Services Implementation Guide. If you want a working sample code, see this project I cooked up. As explained in the guide, what you need to do is to install the service handler:

  - (void)applicationDidFinishLaunching:(NSNotification *)aNotification {

  [NSApp setServicesProvider:self];

  NSUpdateDynamicServices();

  }

  - (void)handleServices:(NSPasteboard *)pboard

  userData:(NSString *)userData

  error:(NSString **)error {

  if([[pboard types] containsObject:NSFilenamesPboardType]){

  NSArray* fileArray=[pboard propertyListForType:NSFilenamesPboardType];

  // do something…

  }

  }

  and advertise it in your Info.plist:

  NSServices

  

  

  NSMenuItem

  

  default

  Service Handling Demo

  

  NSMessage

  handleServices

  NSPortName

  services

  NSSendTypes

  

  NSFilenamesPboardType

  

  

  

  It’s as easy as this! You might need to manually turn on the service entry in the Keyboard Shortcut section of the System Preferences.app. If you want to turn it on automatically, you can write into pbs.plist inside Library/Preferences/, but that’s not a documented way of doing things.

  The problem is that Finder doesn’t show this service item when you right-click an empty region in the Finder window. You can’t do anything with it, other than injecting the code. This is inherent in the Finder’s support of the service system. If you want to change that behavior, you need to inject code inside Finder.app. That’s not that hard. On Snow Leopard, it’s standard to use the OSAX loading trick, described at e.g. in this blog post. Then you can use Objective-C runtime functions to patch the behavior of the right-clicking of the Finder, by changing the methods described in this Apple document. (I don’t know which of the method Finder uses to respond to the right-click event, though.)

  Instead, if you’re OK with clicking a button on the toolbar of the Finder window instead of right-clicking, you can add a button, as in this utility cd-to. This uses the ability to put an icon of the app to the Finder toolbar. The app itself just reads the path of the frontmost Finder window via Apple events, and opens a Terminal window for that. I think you can tweak the code of this app to do what you want.

  Here follow subjective stuffs:

  Honestly, you don’t have to use Objective-C to write a Finder service if you just want to make a new file. Automator can do the same thing with a shell script and/or Applescript.

  If you want to manage files efficiently on Mac, there are already great utilities around: try Butler or launchbar or Quicksilver, for example.

  本文地址:IT屋 ? Writing a Snow Leopard Service for Finder.app

  I’ve currently implemented a simple selection box using mouse events and redrawing a rectangle on mouse drag. Here’s my code:

  -(void)drawRect:(NSRect)dirtyRect

  {

  if (!NSEqualRects(self.draggingBox, NSZeroRect))

  {

  [[NSColor grayColor] setStroke];

  [[NSBezierPath bezierPathWithRect:self.draggingBox] stroke];

  }

  }

  #pragma mark Mouse Events

  - (void)mouseDown:(NSEvent *)theEvent

  {

  NSPoint pointInView=[self convertPoint:[theEvent locationInWindow] fromView:nil];

  self.draggingBox=NSMakeRect(pointInView.x, pointInView.y, 0, 0);

  [self setNeedsDisplay:YES];

  }

  - (void)mouseDragged:(NSEvent *)theEvent

  {

  NSPoint pointInView=[self convertPoint:[theEvent locationInWindow] fromView:nil];

  _draggingBox.size.width=pointInView.x – (self.draggingBox.origin.x);

  _draggingBox.size.height=pointInView.y – (self.draggingBox.origin.y);

  [self setNeedsDisplay:YES];

  }

  - (void)mouseUp:(NSEvent *)theEvent

  {

  self.draggingBox=NSZeroRect;

  [self setNeedsDisplay:YES];

  }

  Ref: http://cocoadev.com/HowToCreateWalkingAnts

  Questions:

  Is this the most efficient way to do this? If the view was complex, would it be more efficient to draw a transparent view over the main view instead of continuously redrawing the view for the duration of the mouse drag (http://www.cocoabuilder.com/archive/cocoa/99877-drawing-selection-rectangle.html)? How is this done? I can’t seem to find any examples.

  You can use QuartzCore to animate the “marching ants” for you, if you want. This gets you completely out of the world of manually drawing the rubber-banded selection box, too. You just define the path that defines that box, and let Core Animation take care of drawing the box, as well as animating it.

  In the XIB’s “View Effects” Inspector, turn on “Core Animation”, and then you can do something like:

  #import

  #import “CustomView.h”

  @interface CustomView ()

  @property (nonatomic) NSPoint startPoint;

  @property (nonatomic, strong) CAShapeLayer *shapeLayer;

  @end

  @implementation CustomView

  #pragma mark Mouse Events

  - (void)mouseDown:(NSEvent *)theEvent

  {

  self.startPoint=[self convertPoint:[theEvent locationInWindow] fromView:nil];

  // create and configure shape layer

  self.shapeLayer=[CAShapeLayer layer];

  self.shapeLayer.lineWidth=1.0;

  self.shapeLayer.strokeColor=[[NSColor blackColor] CGColor];

  self.shapeLayer.fillColor=[[NSColor clearColor] CGColor];

  self.shapeLayer.lineDashPattern=@[@10, @5];

  [self.layer addSublayer:self.shapeLayer];

  // create animation for the layer

  CABasicAnimation *dashAnimation;

  dashAnimation=[CABasicAnimation animationWithKeyPath:@”lineDashPhase”];

  [dashAnimation setFromValue:@0.0f];

  [dashAnimation setToValue:@15.0f];

  [dashAnimation setDuration:0.75f];

  [dashAnimation setRepeatCount:HUGE_VALF];

  [self.shapeLayer addAnimation:dashAnimation forKey:@”linePhase”];

  }

  - (void)mouseDragged:(NSEvent *)theEvent

  {

  NSPoint point=[self convertPoint:[theEvent locationInWindow] fromView:nil];

  // create path for the shape layer

  CGMutablePathRef path=CGPathCreateMutable();

  CGPathMoveToPoint(path, NULL, self.startPoint.x, self.startPoint.y);

  CGPathAddLineToPoint(path, NULL, self.startPoint.x, point.y);

  CGPathAddLineToPoint(path, NULL, point.x, point.y);

  CGPathAddLineToPoint(path, NULL, point.x, self.startPoint.y);

  CGPathCloseSubpath(path);

  // set the shape layer’s path

  self.shapeLayer.path=path;

  CGPathRelease(path);

  }

  - (void)mouseUp:(NSEvent *)theEvent

  {

  [self.shapeLayer removeFromSuperlayer];

  self.shapeLayer=nil;

  }

  @end

  This way, Core Animation takes care of the marching ants for you.

  marching ants demo

  本文地址:IT屋 ? Drawing selection box (rubberbanding, marching ants) in Cocoa, ObjectiveC

  Are there any tutorials describing how to create a library or is it framework for the iPhone? I have a number of methods that are shared between applications. These will be better maintained as a library.

  There is a lot of information on the web that can help with this for example this.

  本文地址:IT屋 ? Creating an iPhone library/framework

  I’m trying to build my first localized application. I have all the strings in code translated using NSLocalizedString (for use with genstrings tool). Now I’m bumping into ibtool. How does incremental localization work? Regarding to the manual page, I should write something like this:

  $ ibtool –previous-file path/to/prev.xib \

  –incremental-file path/to/inc.xib –localize-incremental \

  –write path/to/new.xib mod.xib

  Where do I get the incremental file? To my understanding if I’m using the version control (git/svn), the “old” file is at few commits ago, the incremental file is the diff and path/to/new.xib is newly produced xib file. mod.nib is a mystery to me. Can anyone explain me how this works? Also – how do I start the localization of a xib if no previous versions are available (i.e. doing not incremental, but initial localization)?

  I think their choice of terminology, particularly for –incremental-file, is causing confusion. The idea is that you have an old version of your xib in two languages (source and target) and that you have since changed it in your source-language and want to update the target-language version to match.

  Let’s take an example. You previously had home.xib in English (source language) and got someone to translate it to French (target language). You’ve since developed a new feature and you now have an updated version of home.xib in English in which you added a UILabel and a UITextField and moved things around. The command you showed can help you get an updated version of home.xib in French so that it has the new UILabel and UITextField and that things are moved around like in English. Note that any textual content that you set in your new UILabel and UITextField will be added in English and will then need to be translated in the French xib (but you can automate this by adding –import-strings-file and providing the translations in one more file).

  So if we map the command you showed to this example:

  For your other question regarding how you start the process, really it depends how you will localize your xibs. You’ll obviously create the new language versions of the xibs (in XCode, you just add a language to the language list of the xib and the localized xibs are created automatically). And then if you localize them in Interface Builder yourself, then you’ll simply make the relevant changes (translation of text and any necessary resizing) in the localized xibs. Or you could extract the text in the xibs into .strings files, get them translated, and inject them into the relevant language version of these xibs. For this, again you will use ibtool but with –generate-strings-file for the extract phase and with –import-strings-file for the inject phase.

  本文地址:IT屋 ? How does incremental localization work?

  I’ve got a while loop, that runs for many seconds and that’s why I want to update a progress bar (NSProgressIndicator) during that process, but it updates only once after the loop has finished. The same happens if I want to update a label text, by the way.

  I believe, my loop prevents other things of that application to happen. There must be another technique. Does this have to do with threads or something? Am I on the right track? Can someone please give me a simple example, how to “optimize” my application?

  My application is a Cocoa Application (Xcode 3.2.1) with these two methods in my Example_AppDelegate.m:

  // This method runs when a start button is clicked.

  - (IBAction)startIt:(id)sender {

  [progressbar setDoubleValue:0.0];

  [progressbar startAnimation:sender];

  running=YES; // this is a instance variable

  int i=0;

  while (running) {

  if (i++ >=processAmount) { // processAmount is something like 1000000

  running=NO;

  continue;

  }

  // Update progress bar

  double progr=(double)i / (double)processAmount;

  NSLog(@”progr: %f”, progr); // Logs values between 0.0 and 1.0

  [progressbar setDoubleValue:progr];

  [progressbar needsDisplay]; // Do I need this?

  // Do some more hard work here…

  }

  }

  // This method runs when a stop button is clicked, but as long

  // as -startIt is busy, a click on the stop button does nothing.

  - (IBAction)stopIt:(id)sender {

  NSLog(@”Stop it!”);

  running=NO;

  [progressbar stopAnimation:sender];

  }

  I’m really new to Objective-C, Cocoa and applications with a UI. Thank you very much for any helpful answer.

  If you are building for Snow Leopard, the easiest solution is in my opinion to use blocks and Grand Central Dispatch.

  The following code shows you how your startIt: method would look like when using GCD.

  Your stopIt: method should work fine as you wrote it. The reason why it wasn’t working before is that mouse events happen on the main thread and thus the button didn’t respond to you because you were doing work on the main thread. This issue should have been resolved now as the work has been put on a different thread now with GCD. Try the code, and if it doesn’t work, let me know and I will see if I made some errors in it.

  // This method runs when a start button is clicked.

  - (IBAction)startIt:(id)sender {

  //Create the block that we wish to run on a different thread.

  void (^progressBlock)(void);

  progressBlock=^{

  [progressbar setDoubleValue:0.0];

  [progressbar startAnimation:sender];

  running=YES; // this is a instance variable

  int i=0;

  while (running) {

  if (i++ >=processAmount) { // processAmount is something like 1000000

  running=NO;

  continue;

  }

  // Update progress bar

  double progr=(double)i / (double)processAmount;

  NSLog(@”progr: %f”, progr); // Logs values between 0.0 and 1.0

  //NOTE: It is important to let all UI updates occur on the main thread,

  //so we put the following UI updates on the main queue.

  dispatch_async(dispatch_get_main_queue(), ^{

  [progressbar setDoubleValue:progr];

  [progressbar setNeedsDisplay:YES];

  });

  // Do some more hard work here…

  }

  }; //end of progressBlock

  //Finally, run the block on a different thread.

  dispatch_queue_t queue=dispatch_get_global_queue(0,0);

  dispatch_async(queue,progressBlock);

  }

  本文地址:IT屋 ? How do I update a progress bar in Cocoa during a long running loop?

  I would like to concatenate several PDF files to form one single PDF.

  Now I’ve come so far that I know, PDFKit is the proper way to go (I guess).

  But I am not sure, how to accomplish the merging.

  Should I have one PDFDocument and several PDFPage and then call insertPage on the PDFDocument ?

  Or is there a much simpler way? I dont want to alter the PDFs contetwise, I just want to merge them.

  Thanks a lot!

  As you indicated, you need one output PDFDocument object which will contain all pages of all input PDF files. To do so, you’ll need to loop through all input files, create PDFDocument objects for each one and iterate over all pages to add them using insertPage to the output PDFDocument object.

  Assuming that inputDocuments is an NSArray of one ore more PDFDocument objects, you can use this snippet:

  PDFDocument *outputDocument=[[PDFDocument alloc] init];

  NSUInteger pageIndex=0;

  for (PDFDocument *inputDocument in inputDocuments) {

  for (NSUInteger j=0; j < [inputDocument pageCount]; j++) {

  PDFPage *page=[inputDocument pageAtIndex:j];

  [outputDocument insertPage:page atIndex:pageIndex++];

  }

  }

  本文地址:IT屋 ? Merging PDF Files in Cocoa

  I’ve already spent 2 full days trying to figure out how to use NSViewControllers in order to create a multiview application.

  Here is what I do.

  I have 2 View Controllers and the MainMenu.xib’s Window.

  I also have an AppController that is the delegate for both View Controllers.

  When I launch the app, I’m first greeted with the MainMenu.xib’s Window’s view which holds a button. On clicking this button, an IBAction is sent to the appController and asks for the SecondViewController to display it’s nib. So far, everything’s fine and the nib file is displayed correctly.

  On the secondViewController, there’s another button that sends another IBAction to the appController and asks for the FirstViewController to be displayed but nothing happens,

  no crash, no warning… Any help would be much appreciated…

  Thanks in advance for your patience…

  Here is the code for the AppController.h :

  #import

  #import “SecondViewController.h”

  #import “FirstViewController.h”

  @interface AppController : NSObject

  @property (strong) IBOutlet NSWindow *mainWindow;

  @property (strong) IBOutlet SecondViewController *secondViewController;

  @property (strong) IBOutlet FirstViewController *firstViewController;

  - (IBAction)secondButtonfromsecondViewControllerClicked:(id)sender;

  - (IBAction)buttonClicked:(id)sender;

  @end

  and here is the code for the AppController.m :

  #import “AppController.h”

  @implementation AppController

  @synthesize mainWindow=mainwindow;

  @synthesize secondViewController;

  @synthesize firstViewController;

  - (IBAction)buttonClicked:(id)sender {

  NSLog(@”button from second View Controller clicked”);

  self.secondViewController=[[SecondViewController

  alloc]initWithNibName:@”SecondViewController” bundle:nil];

  self.mainWindow.contentView=self.secondViewController.view;

  [self.secondViewController.view setAutoresizingMask:NSViewWidthSizable |

  NSViewHeightSizable];

  }

  - (IBAction)secondButtonfromsecondViewControllerClicked:(id)sender {

  NSLog(@”button from first ViewController clicked”);

  self.firstViewController=[[FirstViewController

  alloc]initWithNibName:@”FirstViewController” bundle:nil];

  self.mainWindow.contentView=[self.firstViewController view];

  }

  @end

  Well, anyone can help me, I just need a single view application that displays a first ViewController with a button on the first viewController that takes me to a second view controller with a second button that takes me back to my first viewcontroller… I’ve already spent more than a week on that… in vain… PS : I don’t want any button on the mainMenu.xib window nor tabs.

  here is the solution to my question then.

  Here’s the code for the AppDelegate.h:

  // AppDelegate.h

  #import

  #import “FirstViewController.h”

  #import “SecondViewController.h”

  //We need to declare the AppDelegate class as being the delegate for both

  //FirstViewController and SecondViewController

  @interface AppDelegate : NSObject <NSApplicationDelegate,

  FirstViewControllerDelegate, SecondViewControllerDelegate>

  @property (strong, nonatomic) NSWindow *window;

  @property (strong) FirstViewController *firstViewController;

  @property (strong) SecondViewController *secondViewController;

  -(void) goToSecondView;

  -(void) goToFirstView;

  @end

  Now, here’s the AppDelegate.m:

  // AppDelegate.m

  #import “AppDelegate.h”

  @implementation AppDelegate

  @synthesize window=_window;

  @synthesize firstViewController;

  @synthesize secondViewController;

  -(void) awakeFromNib {

  [self goToFirstView];

  self.firstViewController.delegate=self;

  }

  -(void) goToSecondView {

  if (self.secondViewController==nil) {

  self.secondViewController=[[SecondViewController alloc]

  initWithNibName:@”SecondViewController” bundle:nil];

  }

  self.window.contentView=[self.secondViewController view];

  }

  -(void) goToFirstView {

  if (self.firstViewController==nil) {

  self.firstViewController=[[FirstViewController alloc]

  initWithNibName:@”FirstViewController” bundle:nil];

  }

  self.window.contentView=[self.firstViewController view];

  }

  @end

  Next we need to set delegates in the FirstViewController and the SecondViewController

  // FirstViewController.h

  #import

  #import “SecondViewController.h”

  //We declare the delegation protocole:

  @protocol FirstViewControllerDelegate

  -(void)goToSecondView;

  @end

  @interface FirstViewController : NSViewController

  - (IBAction)firstViewControllerButtonClicked:(id)sender;

  @property (nonatomic, strong) id delegate;

  @end

  And here is the FirstViewController.m:

  // FirstViewController.m

  #import “FirstViewController.h”

  @implementation FirstViewController

  @synthesize delegate;

  - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{

  self=[super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];

  if (self) {

  self.delegate=[NSApp delegate];

  }

  return self;

  }

  - (IBAction)firstViewControllerButtonClicked:(id)sender {

  NSLog(@”button from first View Controller clicked”);

  if ([self.delegate respondsToSelector:@selector(goToSecondView)]) {

  [self.delegate goToSecondView];

  }

  }

  @end

  Now, same thing for the SecondViewController:

  // SecondViewController.h

  #import

  @protocol SecondViewControllerDelegate

  -(void)goToFirstView;

  @end

  @interface SecondViewController : NSViewController

  @property (nonatomic, strong) id delegate;

  - (IBAction)goToFirstViewControllerButtonClicked:(id)sender;

  @end

  And here’s the SecondViewController.m:

  // SecondViewController.m

  #import “SecondViewController.h”

  @interface SecondViewController ()

  @end

  @implementation SecondViewController

  - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{

  self=[super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];

  if (self) {

  self.delegate=[NSApp delegate];

  }

  return self;

  }

  - (IBAction)goToFirstViewControllerButtonClicked:(id)sender {

  NSLog(@”button from Second View Controller clicked”);

  if ([self.delegate respondsToSelector:@selector(goToFirstView)]) {

  [self.delegate goToFirstView];

  }

  }

  @end

  Well, I guess this code may be improved and if you have any suggestion, feel free to let me know. Hope it will help others.

  本文地址:IT屋 ? Mac OS X Cocoa multiview application navigation

  My application handles with files of type *.mndl which is not more than a customized *.plist.

  Up until now I’ve been using *.plist files but now I want to associate the extension and be able to open *.mndl files from any other app I have realized that renaming file.plist to file.mndl does not work. (Hence, I don’t even know if I did correctly the extension association and exportation thing)

  I sent to myself a file file.mndl from the computer and when received in mail.app I got

  file.mndl.plist (It was automatically renamed, this happened when reseting my iPad)

  How can I create my own mndl files while being able to read its content using +dictionaryWithContentsOfFile: from NSDictionary class?

  Even I am working with iOS I believe this kind of things were ported from MacOS and Cocoa. So Cocoa developers also could know this.

  Your comments/answers are appreciated.

  Thanks

  ANSWERED:

  Just for completion purposes This is the addition I made to my info.plist:

  UTExportedTypeDeclarations

  

  

  UTTypeConformsTo

  

  public.data

  

  UTTypeDescription

  Mandala Chart File

  UTTypeIdentifier

  com.nacho4d.Accordion.mndl

  UTTypeTagSpecification

  

  public.filename-extension

  mndl

  

  

  

  CFBundleDocumentTypes

  

  

  CFBundleTypeIconFiles

  

  Document320Icon.png

  Document64Icon.png

  

  CFBundleTypeName

  Mandala Chart File

  CFBundleTypeRole

  Editor

  LSHandlerRank

  Owner

  LSItemContentTypes

  

  com.nacho4d.Accordion.mndl

  

  

  

  At least for a Cocoa (desktop) app, you’d want to add the following information to your application’s Info.plist.

  http://www.markdouma.com/developer/nacho.plist

  Obviously, you should change the uniform type identifier to something appropriate. (I usually do com.markdouma.something, since that’s my website).

  Note that you only want to specify an entry for NSDocumentClass if you plan on using Cocoa’s NSDocument architecture by creating an NSDocument subclass to handle loading the files. Otherwise, you could always just implement the following (read that as application delegate protocol) method:

  - (void)application:(NSApplication *)sender openFiles:(NSArray *)filenames;

  That will give you an NSArray of NSStrings representing the POSIX paths to the files the user double-clicked on in the Finder (or dragged to the app icon, etc.)

  If you want to go the NSDocument route, you can override the following method of NSDocument

  - (BOOL)readFromURL:(NSURL *)url ofType:(NSString *)type error:(NSError **)outError;

  and create your dictionary with [[NSDictionary dictionaryWithContentsOfFile:[url path]] retain];

  Hope this helps…

  本文地址:IT屋 ? Creating my own file extension based on plist

  In my iPhone app I want to download multiple files which are on IIS with authentication. On a button click i want to start the downloading process.

  I know how to download a file with authentication.

  NSURLRequest* request= [NSURLRequest requestWithURL:mMovieURL

  cachePolicy:NSURLRequestUseProtocolCachePolicy

  timeoutInterval:60.0];

  movieConnection= [[NSURLConnection alloc] initWithRequest:request delegate:self ];

  and i have couple of delegate methods with the above code.

  But how to do it with mutliple downlaods going at the same time.

  Thanks,

  I’ve done this before when I wanted to download 10 XML files at the same time (it was much faster than queuing them to download one after the other). I used the libraries found here:

  http://github.com/leonho/iphone-libs/tree/master

  They were easy to implement and there’s some example code on the front page to get you started.

  self.urls=[NSMutableArray arrayWithObjects:

  @”http://maps.google.com/maps/geo?output=json&q=Lai+Chi+Kok,Hong+Kong”,

  @”http://maps.google.com/maps/geo?output=json&q=Central,Hong+Kong”,

  @”http://maps.google.com/maps/geo?output=json&q=Wan+Chai,Hong+Kong”,

  nil];

  self.downloads=[[MultipleDownload alloc] initWithUrls: urls];

  self.downloads.delegate=self;

  Good luck.

  本文地址:IT屋 ? Downloading multiple files in iphone app(Objective c)

  I am trying to get the “remaining chars notice” to show up within my rounded NSTextField and I got it with two NSTextFields with help of the Interface Builder and it already looks like that:

  alt text

  But when I write a little bit more it looks like that:

  alt text

  The only thing I could think of is to subclass NSTextField and do something with it so it does not draw text under the number but I have no idea how to begin and need really some help with it.

  The simplest way is probably to subclass NSTextFieldCell and override -drawInteriorWithFrame:inView: and -selectWithFrame:inView:editor:delegate:start:length:.

  You’ll need to decide how much space to allocate for your count and draw in the abbreviated space. Something like this example code should work although this hasn’t been tested in a rounded text field.

  You can find more information about subclassing NSCell in Apple’s PhotoSearch example code.

  - (void)drawInteriorWithFrame:(NSRect)bounds inView:(NSView *)controlView {

  NSRect titleRect=[self titleRectForBounds:bounds];

  NSRect countRect=[self countAreaRectForBounds:bounds];

  titleRect=NSInsetRect(titleRect, 2, 0);

  NSAttributedString *title=[self attributedStringValue];

  NSAttributedString *count=[self countAttributedString];

  if (title)

  [title drawInRect:titleRect];

  [count drawInRect:countRect];

  }

  - (void)selectWithFrame:(NSRect)aRect inView:(NSView *)controlView editor:(NSText *)textObj delegate:(id)anObject start:(NSInteger)selStart length:(NSInteger)selLength {

  NSRect selectFrame=aRect;

  NSRect countRect=[self countAreaRectForBounds:aRect];

  selectFrame.size.width -=countRect.size.width + PADDING_AROUND_COUNT;

  [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(__textChanged:) name:NSTextDidChangeNotification object:textObj];

  [super selectWithFrame:selectFrame inView:controlView editor:textObj delegate:anObject start:selStart length:selLength];

  }

  - (void)endEditing:(NSText *)editor {

  [[NSNotificationCenter defaultCenter] removeObserver:self name:NSTextDidChangeNotification object:editor];

  [super endEditing:editor];

  }

  - (void)__textChanged:(NSNotification *)notif {

  [[self controlView] setNeedsDisplay:YES];

  }

  本文地址:IT屋 ? NSTextField with “padding” on the right

  I have a readonly BOOL property. What is dominant naming pattern here?

  Background: for plain old method declarations, the accepted pattern

  - (BOOL)isEditable;

  - (void)setEditable:(BOOL)flag;

  In a @property world, that would typically be expressed as

  @property(getter=isEditable) BOOL editable;

  However, there are examples to the contrary. Such as in CalStore/CalCalendar.h

  @property(readonly) BOOL isEditable;

  (Is CalCalendar wrong here, or is that the also an acceptable naming pattern for read-only BOOL properties?)

  I’ve got a controller which manages a view, which may or may not be resizable. The property is read only.

  @property(readonly) BOOL viewIsResizable;

  @property(readonly) BOOL isViewResizable;

  @property(readonly, getter=isViewResizable) BOOL viewResizable;

  Which pattern is most natural or Cocoa-like?

  quoted from ADC

  If the attribute is expressed as an

  adjective, the format is:

  - (void)setAdjective:(BOOL)flag;

  - (BOOL)isAdjective;

  For example:

  - (void)setEditable:(BOOL)flag;

  - (BOOL)isEditable;

  If the attribute is expressed as a verb, the format is:

  - (void)setVerbObject:(BOOL)flag;

  - (BOOL)verbObject;

  For example:

  - (void)setShowsAlpha:(BOOL)flag;

  - (BOOL)showsAlpha;

  The verb should be in the simple present tense.

  |K<

  本文地址:IT屋 ? Naming conventions for BOOL Obj-C 2 properties?

  Is there a more straightforward way to wait for a specific amount of time in Cocoa than what I have come up with below?

  - (void) buttonPressed {

  [self makeSomeChanges];

  // give the user some visual feedback and wait a bit so he can see it

  [self displayThoseChangesToTheUser];

  [self performSelector:@selector(buttonPressedPart2:) withObject:nil afterDelay:0.35];

  }

  - (void) buttonPressedPart2: (id)unused {

  [self automaticallyReturnToPreviousView];

  }

  Just to be clear, there is no functional problem with this code — my only beef is a stylistic one. In my case the flow is simple enough that it works, but try to encapsulate it or throw in some conditionals and things could turn ugly. It’s been kind of nagging at me that I couldn’t find a way to wait and then return to that same point in code like this (fictitious) example:

  - (void) buttonPressed {

  [self doStuff];

  [UIMagicUnicorn waitForDuration:0.35];

  [self doStuffAfterWaiting];

  }

  There is

  usleep(1000000);

  and

  [NSThread sleepForTimeInterval:1.0f];

  both of which will sleep for 1 second.

  本文地址:IT屋 ? Waiting for a specified duration in Cocoa

  on the iPhone we have the Apple’s amazing MapKit. There is something similar for Mac OS X?

  If possible something more advanced than a simple WebView, because I need that it manage automatically at least:

  (Even if the maps are not from Google is ok.)

  Thank you very much!

  Update 2

  MapKit is available in OS X 10.9 Mavericks : Map Kit Framework Reference.

  Update – pulled from my comment below

  The situation has changed and there now exists a third party MapKit for Mac OS X. Find it at http://github.com/Oomph/MacMapKit and a small writeup at http://rickfillion.tumblr.com/post/1134987954/pretroducing-mapkit-for-mac

  Orginal Answer

  There is no such API from Apple on Mac OS X. You should file a bug request at bugreporter.apple.com.

  The best alternative is to use the Google Maps JavaScript API embedded in a WebKit view. Visit the Google Maps JavaScript API V3 Documentation to understand the API.

  I realize that you asked for more then a simple WebView, but perhaps you’re unaware of some of the more advance functionality a WebKit view allows.

  Webkit provides means for bridging between the JavaScript scripting environment in your WebKit view and the rest of your Cocoa application.

  To call a Javascript function from Objective-C, use your WebKit view’s WebScriptObject. “Using Javascript From Objective-C” from the “WebKit Objective-C Programming Guide” is a great place to start learning.

  If you need to call back into your Cocoa application from Javascript, “Calling Objective-C Methods From JavaScript” in the “WebKit DOM Programming Topics” provides examples and explanation.

  These technologies used carefully together should provide the functionality you require.

  本文地址:IT屋 ? A MapKit for Mac OS X?

  I want to install and try out the new features of macOS 10.12. Also I really want to work on Xcode 8.0. But the same time I have some client projects which should written on Swift 2.2 [ Xcode 7.3.1 ], I don’t want use Swift 2.3 or Swift 3.0.

  So is it possible to install Xcode 7.3.1 in macOS 10.12? Is there any hacky way to do this?

  Yes I have successfully installed both Xcode 7.3.1 and Xcode 8.0 in my macOS Sierra.

  Now using both Xcodes. But whenever I run my project using Xcode 7.3.1 I am getting this error DTAssetProviderService could not start DTXConnection with Simulator ‘iPhone 6s’. Check the system log for errors. I don’t know the actual reason for this. I have googled for the answers but those suggestions didn’t help me. But at the same time I can run projects in Xcode 8.0 in Simulator, no errors, nothing.

  If anyone came to see this, Please let me know your comment.

  You can absolutely install Xcode 7.3.1 on macOS Sierra alongside the beta version of Xcode 8.

  If you are having issues running Xcode 7.3.x or running the simulator:

  本文地址:IT屋 ? Will Xcode 7.3.1 work on macOS 10.12?

  My iPhone client has a lot of involvement with asynchronous requests, a lot of the time consistently modifying static collections of dictionaries or arrays. As a result, it’s common for me to see larger data structures which take longer to retrieve from a server with the following errors:

  *** Terminating app due to uncaught exception ‘NSGenericException’, reason: ‘*** Collection was mutated while being enumerated.’

  This typically means that two requests to the server come back with data which are trying to modify the same collection. What I’m looking for is a tutorial/example/understanding of how to properly structure my code to avoid this detrimental error. I do believe the correct answer is mutexes, but I’ve never personally used them yet.

  This is the result of making asynchronous HTTP requests with NSURLConnection and then using NSNotification Center as a means of delegation once requests are complete. When firing off requests that mutate the same collection sets, we get these collisions.

  If it’s possible that any data (including classes) will be accessed from two threads simultaneously you must take steps to keep these synchronized.

  Fortunately Objective-C makes it ridiculously easy to do this using the synchronized keyword. This keywords takes as an argument any Objective-C object. Any other threads that specify the same object in a synchronized section will halt until the first finishes.

  -(void) doSomethingWith:(NSArray*)someArray

  {

  // the synchronized keyword prevents two threads ever using the same variable

  @synchronized(someArray)

  {

  // modify array

  }

  }

  If you need to protect more than just one variable you should consider using a semaphore that represents access to that set of data.

  // Get the semaphore.

  id groupSemaphore=[Group semaphore];

  @synchronized(groupSemaphore)

  {

  // Critical group code.

  }

  本文地址:IT屋 ? iPhone use of mutexes with asynchronous URL requests

  I’m trying to release some strain on a view-based NSOutlineView for which I changed a single item property and which I initially reloaded just fine using [myOutlineView reloadData].

  I tried [myOutlineView reloadItem: myOutlineViewItem] but it never calls – (NSView *)outlineView:(NSOutlineView *)ov viewForTableColumn:(NSTableColumn *)tableColumn item:(id)item and consequently the data is not updated.

  -(void)reloadOutlineViewObject

  {

  //[myOutlineView reloadData]; //Reload data just fines but is ressource-hungry

  NSLog(@”%d”,[myOutlineView rowForItem:myOutlineViewItem]; //Making sure my object is an item of the outlineView, which it is !

  [myOutlineView reloadItem:myOutlineViewItem];

  }

  Am I missing something here ?

  As pointed out in the comments, my outlineView is view-based.

  Trying out some stuffs made me realized that the object I am reloading is a second-level object (cf object tree) and calling reloadItem:firstLevelObject reloadChildren:YES does work.

  Would it be possible that we can only call reloadItem: on first-level object ? That would be highly inefficient in my case (I only have one two level item and plenty of second level) !

  nil ->firstLevelA ->secondLevel1

  ->secondLevel2

  ->firstLevelB ->secondLevel3

  ->secondLevel4

  Gonna try to subclass NSOutlineView and rewrite reloadItem: in the mean time.

  I took a look at NSOutlineView in Cocotron to get start and felt that the code I needed to write to overwrite reloadItem would be quiet heavy. Anyone to confirm ?

  I encountered this same problem with a view-based outline view, where calling -reloadItem: seems to just not do anything. This definitely seems like a big bug, though the documentation doesn’t explicitly say that reloadItem will reacquire the views for that row.

  My workaround was to call NSTableView’s -reloadDataForRowIndexes:columnIndexes: instead, which seems to work as expected, triggering a call to the -outlineView:viewForTableColumn:item: delegate method for just that item. You can get the row that needs to be reloaded by calling -rowForItem: and passing in the item you want to reload.

  本文地址:IT屋 ? NSOutlineView reloadItem: has no effect

  Why do Objective-c objects have to be dynamically allocated? Why do I have to make it a pointer to an object, unlike in C++ I can create them on stack?

  Thanks.

  the primary reason: not knowing how much stack size to reserve.

  existing conventions and uses also make lifting the restriction quite difficult.

  dynamic messaging does not matter in this case, as setting the right ‘vtable’ at initialization is trivial.

  in c++, the size of a stack object is always known (and if it’s wrong, you know what to expect). an objc alloc/init sequence can return any one of several types — each with different sizes (it’s essentially a factory), or nothing at all.

  the size can also vary at runtime (e.g. you can add fields to a class via the runtime).

  Update 1

  i was curious about this, so i made a little test program as a proof of concept.

  i was able to implement a simple stack based objc class hierarchy, which also implemented a good chunk of NSObject’s interface — of course, omitting the reference counting and dynamic allocation interfaces as it did not relate to the proof of concept. at any rate, my simple class hierarchy was not fully compatible with the NSObject class or protocol, so it isn’t something that should be used where NSObject types are expected, for obvious reasons. therefore, it is possible (and not particularly difficult) to accomplish this, if you really wanted stack based objc objects.

  you don’t have to do anything different from c++ to reserve the stack space. the stack size to reserve is still a restriction in some areas (consider factory methods, class clusters, etc.).

  there are also a few runtime functionalities which will not work by default. the best example here is the ability to add ivars at runtime. you could in fact accomodate this functionality, if you needed it. i didn’t bother with that exercise.

  naturally, the base interface could take several deviations – one deviation that i made for fun was adding the ability to exchange the implementations (type) of a living object.

  have fun

  Update 2

  as it turns out, GCC accepts the proof of concept i wrote. unfortunately, this has been banned in clang due to problems/dangers which can be encountered in reserving the correct size (considering the dynamic features of the language…). example: clang forbids sizeof(NSObject). oh well.

  本文地址:IT屋 ? Why do Objective-C objects have to be dynamically allocated?

  I found this wonderful NSManagedObjectID. This would be very good for referencing an Entity/NSManagedObject/NSEntityDescription, right?

  Let’s get an ID from an entity:

  NSEntityDescription *entity=[self newEntity];

  NSManagedObjectID *objID=[entity objectID];

  So… any idea how to get this objID into a string? Or better: NSData. Actually something to be able to save it to the NSUserDefaults. 😉

  Btw: NSFetchRequest doesn’t want to work in my case. I use an modified version of this example: answer of an old question.

  To get an archived URI corresponding to a NSManagedObject’s objectID:

  NSManagedObject* myMO;

  …

  NSURL *uri=[[myMO objectID] URIRepresentation];

  NSData *uriData=[NSKeyedArchiver archivedDataWithRootObject:uri];

  In order to get back to an instance of the original managed object, you need a CoreData stack with the persistent store holding that instance already added to the NSPersistentStoreCoordinator. Then:

  NSData *uriData;

  NSPersistentStoreCoordinator *psc;

  NSManagedObjectContext *moc; //with moc.persistentStoreCoordinator=psc.

  …

  NSURL *uri=[NSKeyedUnarchiver unarchiveObjectWithData:uriData];

  NSManagedObjectID *moID=[psc managedObjectIDForURIRepresentation:uri];

  NSManagedObject *myMO=[moc objectWithID:moID];

  本文地址:IT屋 ? NSManagedObjectID into NSData

  I have developed in C++ many years ago, but these days I am primarily a Java software engineer. Given I own an iPhone, am ready to spring for a MacBook next month, and am generally interested in getting started with Mac OS developmentmt (using Objective C), I thought I would just put this question out there: What Next?

  More specifically, what books should I pick up, and are there any web resources that some folks could point me to? Some books that I am planning to purchase:

  Anyone familiar with these titles? Finally, I would be very interested in a summary of what I should be prepared to expect, once I embark on this journey. As someone that develops in Java using IntelliJ IDEA, what are some key differences I will notice as I move over to writing ObjectiveC code in Xcode? What’s the differences between Mac OS desktop development and iPhone development? Being used to Java garbage collection, what should I know about ObjectiveC garbage collection / memory management. Any other language specific issues that anyone would like to point out? How about building UIs? Is it closer to Swing, building Visual C++ resource files that code interacts with, or is it more like some of the borland IDEs that will generate code for guis?

  Having purchased both of the books in your question, I recommend Cocoa Programming for Mac OS X as a quick way to learn the language and the Cocoa framework, and is probably the fastest way to start producing real applications in Cocoa. I highly recommend it. Programming in Objective-C 2.0 is a great reference book, but if you already know C, there’s no much it’s going to teach you that you can’t pick up from the other book. However, if you ever need to a list of all the reserved keywords in Objective-C, that’s the book to go to.

  All of the user interface can be generated progmatically, but you’ll find it much easier to use Interface Builder, which comes with XCode, to lay out the user interface. You’ll end up with a lot less code. With bindings, you can even eliminate code which isn’t directly related to laying out the interface. The details are in the Cocoa Programming for Mac OS X book.

  The one big thing I miss from Java is the collection API. In Cocoa, you just get NSSet, NSArray, and NSDictionary, and there’s no analog to the Comparable interface. These classes are also immutable, but have mutable versions such as NSMutableArray.

  I actually haven’t played with the Garbage Collection in Objective-C 2.0. In previous versions of Objective-C, memory management was handled by the retain, release, and autorelease methods. Objects were created with a retain count of 1. Retaining incremented that count, releasing decremented it, and autoreleasing objects is a little more complicated. Again, the Cocoa Programming book explains it well. Garbage collection is an option, and if it’s turned on, the retain, release and autorelease methods do nothing. However, if you are writing a library or framework to be used by others, you should program it as if garbage collection is turned off. That way applications can use it whether or not they have garbage collection turned on.

  As for Web resources, http://cocoadevcentral.com/ is a great site with beginner tutorials. The CocoaDev Wiki at http://www.cocoadev.com/ contains detailed information on a lot of topics, and you can usually find some useful information and people on the cocoa-dev mailing list http://lists.apple.com/mailman/listinfo/cocoa-dev

  iPhone development is a little different, and the details are restricted by an NDA. However, if you get approved by Apple to get access to the iPhone developer center, Apple has provided some great video overviews of the differences, which point you to the documentation you need to make the jump from Mac OS X to iPhone OS X programming.

  本文地址:IT屋 ? Java Developer meets Objective-C on Mac OS

Have any Question or Comment?

发表评论

电子邮件地址不会被公开。 必填项已用*标注

友情链接:

fun88 bbin 凯时国际娱乐 澳门博彩 皇家88娱乐