Re: archiving report

2013-02-26 Thread Gwynne Raskind
On Feb 26, 2013, at 12:47 PM, Gerriet M. Denkmann gerr...@mdenkmann.de wrote:
 My investigations regarding archiving on OS X:
 
 1. NSArchiver stores all strings in Utf-8.
   This is inefficient for strings which contain mainly non-european 
 characters (e.g. Chinese or Thai) as one character will use 3 bytes (Utf-16 
 would use only 2).
   Corollary: It cannot store strings which contain illegal Unicode chars.

And then in UTF-16, strings which contain mostly ASCII/European characters are 
wasting 2x space. Six of one, half dozen of the other. This is a very old 
debate and I'm grateful that Apple chose UTF-8 for storage, as UTF-16 makes 
things much more complicated.

 2. NSKeyedArchiver seems to be ok.
   But it does create unnecessary data. E.g. in the case of an array 
 containing identical objects, like:
   NSArray *a = @[ @a, @a, , @a];
   With 1 000 000 items it creates 10,000,395 bytes - my version creates 
 only 1 000 332 bytes 
   and the output is still readable by NSKeyedUnarchiver.

Are you sure this is happening? NSKeyedArchiver is documented as doing 
deduplication of objects. If this is true, it's definitely a bug and there is 
no reason Apple wouldn't want it fixed.

 3, NSKeyedUnarchiver has several bugs.
   The string $null is converted to nil. 
   Very harmful if this string is part of a collection (like array, set or 
 dictionary).

It should have already been mangled by NSKeyedArchiver.

   If the key in: encodeXXX:forKey: starts with an $ NSKeyedArchiver 
 correctly mangles this by prefixing
   another $. But NSKeyedUnarchiver does not find these mangled keys and 
 returns nil or 0.

You can, as a workaround, consider keys prefixed by $ as reserved, however this 
is certainly a bug. The fact that no one has reported it/gotten it fixed in so 
much time shows that it's probably not a major issue, though.

 I have not reported these bugs, as I am convinced that Apple has no interest 
 in fixing these problems.

This is the exact attitude that causes Apple to be perceived as not having 
interest. Please file the bugs - the engineers reading this list can't give 
high priority to things that developers don't report, as much as they'd 
probably like to.

-- Gwynne Raskind


___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Re: am I being called on the correct GCD queue?

2013-02-09 Thread Gwynne Raskind
The replacement I've seen for checking whether the current queue is correct 
for the code in which it's running looks something like this (for a complete 
implementation example, see GCDAsyncSocket):

static char *kMYObjectIsOnItsOwnQueueKey = Whatever:

- (instancetype)init
{
if ((self = [super init])) {
// ...
_myQueue = dispatch_queue_create(...);
dispatch_queue_set_specific(_myQueue, 
kMYObjectIsOnItsOwnQueueKey, (__bridge void *)self, NULL);
}
return self;
}

- (BOOL)isExecutingOnMyQueue
{
return dispatch_get_specific(kMYObjectIsOnItsOwnQueueKey) == (__bridge 
void *)self;
}

-- Gwynne Raskind

On Feb 9, 2013, at 7:19 PM, Kyle Sluder k...@ksluder.com wrote:

 On Feb 9, 2013, at 12:11 PM, Matt Neuburg m...@tidbits.com wrote:
 
 If dispatch_get_current_queue() is deprecated
 
 It's not deprecated in any currently non-NDA'd SDK.
 
 
 how can I check whether this method is being called on the right dispatch 
 queue? For example, I'd like to throw a wobbly (an assertion, maybe) if this 
 method is called on any queue whose label isn't com.neuburg.myCoolQueue. 
 Is that a wrong thing to want to do? Thx - m.
 
 Maybe dispatch_queue_specific can be used here?
 
 --Kyle Sluder
 ___
 
 Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)
 
 Please do not post admin requests or moderator comments to the list.
 Contact the moderators at cocoa-dev-admins(at)lists.apple.com
 
 Help/Unsubscribe/Update your Subscription:
 https://lists.apple.com/mailman/options/cocoa-dev/gwynne%40darkrainfall.org
 
 This email sent to gwy...@darkrainfall.org


___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Re: Could somebody please fix NSTimer?

2013-01-12 Thread Gwynne Raskind
On Jan 12, 2013, at 2:05 PM, Kyle Sluder k...@ksluder.com wrote:
 On Jan 12, 2013, at 10:49 AM, Gordon Apple g...@ed4u.com wrote:
 
 When compiled under ARC, NSTimer should have a weak, not strong, reference
 to its target.  When the timer starts to fire, check the reference for nil
 and invalidate itself.  Come on guys, how hard is that?  You wouldn¹t even
 have to keep a reference to it, unless you want to invalidate it before the
 target deallocates.
 
 You should already be invalidating it before the target deallocates…

Not to mention, just use a dispatch timer:

// THIS ASSUMES ARC
dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 
0, dispatch_get_main_queue());

dispatch_source_set_timer(timer, dispatch_time(DISPATCH_TIME_NOW, 
myFiringInterval * NSEC_PER_SEC), myFiringInterval * NSEC_PER_SEC, 
1/*leeway*/);
__typeof__(self) __weak w_self = self;
dispatch_source_set_event_handler(timer, ^ {
 __typeof__(self) __strong s_self = w_self;
 if (!s_self) {
  dispatch_cancel(timer);
  return;
 }
 /* do your stuff here, make sure you use s_self instead of self */
});
dispatch_source_set_cancel_handler(timer, ^ {
 dispatch_source_set_event_handler(timer, NULL);
 dispatch_source_set_cancel_handler(timer, NULL); // kill the cycle
});
dispatch_resume(timer);

Boom, self-destructing timer. Warning: Written in Mail and totally untested. 
Also, don't do this, just manage your timers properly.

-- Gwynne Raskind


___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Re: NSMutableData and Pinned Memory buffers..

2012-12-13 Thread Gwynne Raskind
On Dec 13, 2012, at 7:28 PM, Kevin Perry kpe...@apple.com wrote:
 On Dec 13, 2012, at 4:24 PM, Greg Parker gpar...@apple.com wrote:
 On Dec 13, 2012, at 4:13 PM, Robert Monaghan b...@gluetools.com wrote:
 I went ahead and created a really crude subclass of NSMutableData. It seems 
 to work for my situation.
 Attached is the code, for posterity. (I am sure I won't be the only one 
 working around this.)
 
 Any suggestions to make this a bit more Proper are welcome.
 If that's all you need then you should wrap the buffer in an immutable 
 NSData. NSData won't mind if you poke directly at the contents of the buffer.
 Except that he's probably expecting to be able to invoke -mutableBytes and 
 modify the buffer's contents without changing the length. Immutable NSData 
 objects don't respond to -mutableBytes.

In this case, you could do this, as ugly as it is (and it also violates LSP, as 
it changes the behavior of all NSData objects, though that's unavoidable due to 
the class cluster anyway; depending on an immutable NSData to throw an 
exception on receiving -mutableBytes would be so wrong I don't think it's that 
bad to break it).

@interface NSData (MutableImmutable)
- (void *)mutableBytes;
@end

@implementation NSData (MutableImmutable)
- (void *)mutableBytes {
#if __cplusplus
return const_castvoid *(self.bytes);
#else
return (void *)self.bytes;
#endif
}
@end

-- Gwynne Raskind


___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Re: blocks and id

2012-12-12 Thread Gwynne Raskind
On Dec 12, 2012, at 6:36 AM, jonat...@mugginsoft.com wrote:
 On 12 Dec 2012, at 09:57, Andreas Grosam agro...@onlinehome.de wrote:
 On 12.12.2012, at 10:19, Charles Srstka wrote:
 On Dec 12, 2012, at 3:03 AM, Andreas Grosam agro...@onlinehome.de wrote:
 
 How can I check at runtime whether an object (id) is actually a block, and 
 not another kind of object?
 
 I don't think there's any good way of doing that right now. You could check 
 the class of the block, but since the block classes are completely 
 undocumented AFAIK, there's no guarantee that the class names won't change 
 in some future release of OS X and break your code.
 Thanks for the reply. I feared that. 
 
 Currently, I resort to 
 
 
 if ([obj isKindOfClass: NSClassFromString(@NSBlock)])
 …
 
 which evaluates to YES if `obj` is a block. However, NSBlock is not a public 
 class, thus: NSClassFromString(@NSBlock) which works as the time of 
 writing in Mac OS, and returns a class whose name is NSBlock (the real 
 block classes are named differently).
 
 I wish there was something official.
 You could perhaps make this a little less fragile.
 
typedef void (^MyBlockType)(void);
 
// we know this is a block
void (^isaBlock)(void) = ^(void) {};
 
MyBlockType aBlock = ^(void) {NSLog(@I am a block);};
 
id qua = aBlock;
 
if ([qua isKindOfClass:[isaBlock class]]) {
   ((MyBlockType)qua)();
}

This will not work for all cases. For example, a stack-based block versus one 
that's been copied to the heap will have different classes, which are probably 
siblings (i.e. [[_NSConcreteStackBlock class] isKindOfClass:[_NSMallocBlock 
class]] == NO).

My solution to this issue has been the exclusion case, i.e. if (![obj 
isKindOfClass:[anything my API contract says I can receive that isn't a 
block]]) { /* it's a block by process of elimination */ }. Obviously this won't 
work if your API contract says you can receive arbitrary objects.

-- Gwynne Raskind


___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Re: REST, SOAP, XML-RPC, ...?

2012-11-04 Thread Gwynne Raskind
On Nov 4, 2012, at 7:12 PM, Todd Heberlein todd_heberl...@mac.com wrote:
 Is there currently a standard, Apple-recommended way of doing interoperable 
 client-server architectures?

Nope.

 I accidentally backed into a solution that is Apache, PHP, and libcurl, and I 
 figured I should go with one of the many standards out there. REST is pretty 
 close to what I am already doing, and looks nice, clean, and simple.
 
 But are there some nice client-side APIs that Apple recommends I use that 
 will make it easier to build Mac and iOS applications that use some 
 particular web service protocol?  And if so, are these some server-side APIs 
 (???) that I can use on the web server side?

There are no Apple recommendations, but I'm personally fond of RESTKit 
(http://restkit.org). I tend to eschew its object mapping abilities in favor of 
the straight-up REST requests and responses; in this mode it presents a much 
(IMO) friendlier wrapper around NSURLConnection and NSURLRequest.

As for server APIs, I've always just written my own very simple REST router in 
PHP when needed; I've worked almost exclusively with servers implemented by 
others, so I can't speak to what's good there.

HTH!

-- Gwynne Raskind
___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Re: Macro challenge with variable arguments

2012-11-01 Thread Gwynne Raskind
On Nov 1, 2012, at 10:15 PM, Graham Cox graham@bigpond.com wrote:

 Hi all, I'm having trouble figuring this out.
 
 I have a logging function thus:
 
   voidGCLogObjCMethod( id obj, SEL selector, NSUInteger lineNumber, 
 NSString* tag, NSString* format, ... );
 
 I'd like to be able to wrap this using a macro that automatically supplies 
 the object, selector, line number and 'tag' (which is usually the class name 
 of the object) and leaves only the format and the variable arguments to be 
 supplied. I haven't been able to come up with a way that works. Can it be 
 done? i.e. what I want is a macro:
 
 GCLOGOC( @this is a format string: %@, with any number of params: %@, 
 paramA, paramB );
 
 and this expands to:
 
 GCLogObjCMethod( self, _cmd, __LINE__, NSStringFromClass([self class]), 
 @this is a format string: %@, with any number of params: %@, paramA, paramB 
 );
 
 (or expands to nothing at all if logging has been turned off).
 
 How can I define the macro so it can handle the variable parameter list?

#if LOGGING
#define GCLOGOC(format, ...) GCLogObjCMethod(self, _cmd, __LINE__, 
NSStringFromClass([self class]), format, ## __VA_ARGS__)
#else
#define GCLOGOC(format, ...)
#endif

-- Gwynne Raskind


___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Re: 32-bit on 10.8

2012-08-11 Thread Gwynne Raskind
On Sat, Aug 11, 2012 at 1:38 PM, Jayson Adams jay...@circusponies.com wrote:
 I say again, Apple's official 64-bit porting document states, right now, that 
 you may or may not want to move to 64 bit.  If Apple is planning on removing 
 32-bit support in the near future, they will be partly to blame for any rude 
 surprise to developers.  You can talk all you want about reading the tea 
 leaves to determine the time of 32-bit's last breath, but not every developer 
 is doing that. The ones who aren't, but are consulting the porting guide, 
 have a different understanding of the situation.

You've already been told, by Apple people and others, that that guide
is completely outdated. This is not a joke, this is not a guess or a
conjecture or an extrapolation; this is fact. That advice is no longer
relevant. Porting to 64-bit is not optional going forward. 32-bit
support is already waning in current versions of the OS and Apple has
all but explicitly stated they don't intend to do anything about it
and DO intend to drop the support in the future.

If you treat this as anything other than a reason to make the effort
now, while you still have a working application and don't have to
leave your users hanging waiting for a new version, then you are
saying that you -want- to fail. No more, no less.

64-bit porting is not a complicated endeavor for most applications,
and while I can speak with certainty only for myself, I'm sure many
people on the list would be more than happy to offer you advice on any
areas you find problematic if you would explain where you foresee
difficulties.

-- Gwynne

___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Re: Why Don't Cocoa's (Un)Archiving Methods return Errors?

2011-07-29 Thread Gwynne Raskind
On Fri, Jul 29, 2011 at 21:48,  wadesli...@mac.com wrote:
 Granted that NSKeyedUnarchiver might have left some memory leaks or 
 partially uninitialized objects somewhere, but unarchiving an invalid object 
 should happen rarely if at all... and ordinarily my own code should never 
 get pointers to such objects, anyway.
 Indeed there may be memory leaks, but that's a relatively benign side effect. 
  The security issues I alluded to earlier are a much greater concern in any 
 case.

Can you be more specific about those side effects? I'm rather curious,
and somewhat concerned; I've used NSCoding in the past for persisting
data.

-- Gwynne
___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Re: Help Mixing Objective-C Objective-C++

2011-02-24 Thread Gwynne Raskind
On Feb 24, 2011, at 3:58 AM, Andreas Grosam wrote:
 You can't, but you can declare protocols for your ObjC++ classes in separate 
 headers then have the ObjC classes interact with NSObjectFoo instead of 
 Foo objects directly.
 
 FooProtocol.h
 
 @protocol Foo
 // methods the pure ObjC classes need to see 
 @end
 
 Foo.h
 
 #import FooProtocol.h
 @interface Foo : NSObject Foo
 ...
 
 Foo.mm
 #import Foo.h
 // do C++ things here
 
 Bar.m
 
 #import FooProtocol.h
 // do things with NSObjectFoo 
 This would be an excellent approach, since protocols are the real and pure 
 interfaces  -- like formal duck-typing  :)
 
 However, with protocols alone you cannot create objects - you need some sort 
 of factory method, declared in some other class:
 
 idFoo myFooObject = [someObject newFoo];
 
 Note: someObject can be a class object or an instance object. It just needs 
 to implement the factory methods. The resulting object can be an instance of 
 any class, it doesn't need to be class Foo.


You can use protocols alone to do object creation with a little runtime 
trickery. I'm quite fond of this small set of language extensions:

http://code.google.com/p/libextobjc/

For this situation, I was thinking of the concrete protocol implementation 
provided by the library, which I've used several times to plug functionality 
into classes when I couldn't change the inheritance. Other languages call these 
traits.

(And while on the subject of language extensions, I also shamelessly plug for 
Michael Ash's MAGenerator class. +1 to get both that and libextobjc constructs 
into Objective-C 3.)

-- Gwynne

___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Re: info.plist with DYLD_LIBRARY_PATH = ~/test

2010-10-02 Thread Gwynne Raskind
On Oct 2, 2010, at 7:20 AM, Ken Thomases wrote:
 Sorry to be obtuse, but it may be that I am overlooking something. 
 Presently, we have calls such as
 
 n = PyNumber_Float(obj)
 s = PyString_AsString(obj)
 
 I understand that I would need to generate #defines for all those names, 
 such as PyNumber_Float to map them to some table. I would have to initialize 
 that table in a big for loop that goes through another table containing the 
 name of each function (e.g. PyNumber_Float. The loop then looks each name 
 up with dlsym and initializes the table.
 
 Or can this be done more elegantly?
 Declare function pointers:
 
 typeof(PyNumber_Float) *pPyNumber_Float;
 typeof(PyString_AsString) * pPyString_AsString;
 
 This can be table-ized with a macro:
 
 #define DOFUNC(f) typeof(f) *p##f
   DOFUNC(PyNumber_Float);
   DOFUNC(PyString_AsString);
   // ...
 #undef DOFUNC
 
 
 During initialization, dynamically load the Python framework with dlopen().  
 Then, load the function pointers by looking up the symbols:
 
 pPyNumber_Float = dlsym(handle, PyNumber_Float);
 pPyString_AsString = dlsym(handle, PyString_AsString);
 
 This can be table-ized with a macro:
 
 #define DOFUNC(f) do { if (!(p##f = dlsym(handle, #f))) { \
   fprintf(stderr, Failed to load %s\n, #f); \
   goto bail; \
 } while (0)
   DOFUNC(PyNumber_Float);
   DOFUNC(PyString_AsString);
   // ...
 #undef DOFUNC
 
 
 Notice that the table within the definitions of DOFUNC is identical in both 
 cases.  So, you can extract it to a separate file and #include it between the 
 DOFUNC #define and #undef:
 
 #define DOFUNC(f) /* whatever */
 #include PythonFunctionDoFuncs.h
 #undef DOFUNC
 
 That way there's just the one table for both purposes.
 
 
 Then, you have two choices.  1) Throughout your code, call the functions with 
 the function pointers.  This basically entails prepending a p to all the 
 function names.  2) Use macros to do this for you:
 
 #define PyNumber_Float pPyNumber_Float
 #define PyString_AsString pPyString_AsString
 
 I can't think of a technique to table-ize the above.  There may be one that 
 I'm forgetting, but I don't think so.  Still, that's just two places to touch 
 for each Python function you use.
 
 If you want to get fancier, you could have a single file which just lists the 
 Python functions you use, one per line.  Then, a script would generate both 
 the PythonFunctionDoFuncs.h and a PythonFunctionRedefines.h (with the above 
 macro definitions) from that list.


#!/usr/bin/env lua

funcs = 
loaders = BOOL\tPython_LoadFunctions()\n{\n
defs = 
for line in io.lines(PythonFunctions.def) do
funcs = funcs .. string.format(typeof(%s) *p%s\n, line, line)
loaders = loaders .. string.format(if (!(p%s = dlsym(handle, 
\%s\)))\n{\n ..
fprintf(stderr, Failed to load %s\n);\ngoto bail;\n}\n, 
line, line, line)
defs = defs .. string.format(#define %s p%s\n, line, line)
end
loaders = loaders .. return YES;\nbail:\nreturn NO;\n}\n

io.open(PythonFunctions.h, w):write(funcs .. \n .. loaders .. \n .. 
defs)
-- EOF

Disclaimer: Written entirely in Mail and untested. Lua is not installed by 
default on Mac OS! Do it in Python instead, which I don't know enough to give 
the example in.

Set up an Xcode build rule in your target for files matching the pattern 
PythonFunctions.def and containing this script, with 
$(DERIVED_FILES_DIR)/PythonFunctions.h as the output file. Then #include the 
file in your source; Xcode should do the right thing from there.

-- Gwynne

___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Re: -forwardInvocation: like NSInvocation creation

2010-03-31 Thread Gwynne Raskind
On Mar 31, 2010, at 2:26 AM, Philip Mötteli wrote:
 Another alternative would be to combine method_getNumberOfArguments() and 
 method_copyArgumentType() with ffi_prep_cif() and ffi_call(), which I think 
 is what libobjc itself does these days. libffi is available since at least 
 10.5. Pass the method's IMP to ffi_call() and don't forget to adjust the 
 call to ffi_prep_cif() for the hidden self and _cmd arguments. 
 That's the way I would have to go, if I would have to re-implement, what 
 Apple already has done for -forwardInvocation:. That's also, what GNUstep 
 does. I think libffi or the other library, that has the same purpose, I 
 forgot its name, are even made by GNUstep.
 It's just a pity, to reinvent the wheel. I mean, we're talking OO here, reuse 
 of code and not continuous rewriting.

I would guess that they pulled direct support for it out of NSInvocation and 
the runtime API because 1) it involves parsing Objective-C type encoding 
strings, and 2) it's unsafe to save stack frames (more below). Based on some of 
the changes they made in the modern runtime and the consistent lack of complete 
documentation of the contents, I suspect they're trying to get people to 
consider encoding strings as entirely opaque objects, much like selectors.

I even tend to agree with the sentiment, as using them for a case like this has 
its pitfalls and difficult edge cases. One example would be having a forwarder 
which returns a structure which doesn't fit in a GPR or on PPC in general. 
objc_msgSend_stret() handles this by returning the structure in a hidden 
pointer parameter. The PPC ABI demands a memory allocation with a pointer 
passed in a specific GPR, i386 copies it on the stack, x86_64 can put it in a 
register or on the stack depending on size and ordering. I don't remember what 
arm does, but I'd guess offhand it makes use of the red zone for the purpose. 
Only the compiler knows for certain exactly what choice was made for any given 
situation, short of someone reimplementing the target ABI's logic.

Keep in mind that even if you get it working, from what your post said you're 
trying to save off a stack frame for later use. Any pointers and objects saved 
in the frame will have unpredictable lifetimes outside the forwarder call (even 
in functions called from it) unless very carefully managed. Under GC you'll 
have to allocate the memory for your ffi structures as scanned and collectable, 
or call retain on any passed-in objects under RR. Non-object pointers are just 
plain unsafe unless you can somehow guarantee their lifetimes for the existence 
of your saved frame; for exmaple, this would be just plain impossible if the 
forwarder were called with a parameter like addressOfLocalVariable. In the 
end it's rarely feasible to actually save a call for indeterminate future use 
outside the call. C and Objective-C are just too low level.

It's closely related to why it took so long for blocks to be implemented and 
why memory management questions about them keep cropping up.

-- Gwynne



smime.p7s
Description: S/MIME cryptographic signature
___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Re: -forwardInvocation: like NSInvocation creation

2010-03-30 Thread Gwynne Raskind
On Mar 30, 2010, at 2:54 PM, Michael Ash wrote:
 I see, I really wasn't enough clear. Lets say, I have a method
 
 - someMethodWithArgument:(struct *)anArgument 
 andSomeOtherArgument:(id)anotherArgument
 {
// Here I want to create an NSInvocation, capturing the call of this 
 method. Something like:
NSInvocation *anInvocation = [NSInvocation initWithArgframe: 
 (arglist_t)frame selector: _cmd];
 }
 I don't think that such a thing is possible in the general case
 without compiler support, because once your function begins executing,
 there's no guarantee that the arguments remain in their original
 locations on the stack frame. (Especially true on PPC and x86_64,
 where arguments are frequently passed in registers.) And no such
 compiler support exists.
 
 I'd say that your best bet is probably to do some fancy method
 replacement stuff so that your IMP gets replaced with the forwarding
 IMP, then your -forwardInvocation: method can store the invocation
 somewhere and then pass control over to the real method, where it can
 retrieve it.


Another alternative would be to combine method_getNumberOfArguments() and 
method_copyArgumentType() with ffi_prep_cif() and ffi_call(), which I think is 
what libobjc itself does these days. libffi is available since at least 10.5. 
Pass the method's IMP to ffi_call() and don't forget to adjust the call to 
ffi_prep_cif() for the hidden self and _cmd arguments. libffi is available at 
least since 10.5.

-- Gwynne



smime.p7s
Description: S/MIME cryptographic signature
___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Re: Better sorting using threads?

2010-03-12 Thread Gwynne Raskind
On Mar 12, 2010, at 2:25 AM, Ken Ferry wrote:
 Does Cocoa have sorted containers so that an object can be inserted in
 sorted order?  If so it seems like this would be far less expensive.
 
 Probably the best thing to do if you want this is to maintain the sort
 yourself by inserting new objects in the correct position.  You can find the
 position using
 -[NSArray indexOfObject:inSortedRange:options:usingComparator:].  That's two
 lines instead of one to add an object to an array, which is not bad.
 
 That method is new in 10.6, but something similar has been in CoreFoundation
 for a while.  CFArrayBSearchValues is usable on NSArray since CFArray is
 bridged.
 
 You can also look at -[NSArray sortedArrayHint].  The deal there is that you
 extract an opaque hint from a sorted array, change the array, and resort
 passing in the hint.  This is optimized for the case when the array is still
 mostly sorted, but with some things out of place.

I maintain a simple sorted array by rerunning -sortUsingFunction:context: for 
every insert (or set of inserts, since the vast majority of inserts into the 
array are groups of objects together). So far I haven't had any speed issues 
with it at all. But my case is pretty simple; it's a small array of around 100 
objects, and the sort function is trivial (object.integerProperty comparison).

-- Gwynne

___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Key-Value Observing speed

2010-03-12 Thread Gwynne Raskind
While profiling a project I'm working on, I found that while most of my time 
was being spent in glFlush() (which is completely expected for an OpenGL-based 
game), a non-trivial amount of time is being spent in dozens of KVO internal 
methods and functions. Most especially, I noticed that KVO (or possibly the KVC 
beneath it) makes heavy use of NSInvocation-based forwarding, which is known to 
be the slowest possible code path for message dispatch.

KVO is central to my code's structure; I rely on it for everything to know what 
everything else is doing without sprinkling manual notifications all over the 
code. Is there any way to trick the runtime into taking some faster code paths? 
It's really troublesome to see property setter methods taking up almost as much 
total time as the audio converter thread in Instruments. Would it help if my 
properties were sets of integers instead of structures (specifically, NSPoint 
and NSRect are used quite a bit)? Would it be just blindly insane to think that 
a NSRectObject would be faster somehow than a plain NSRect because of the 
structure return trickery the runtime has to do?

And if there's nothing I can do with Apple's KVO, is it even remotely realistic 
to consider writing my own quickie version of KVO that takes faster paths since 
I can tweak it for my uses?

(Side note, Michael Ash's MAKVONotificationCenter has been a panacea for all 
manner of minor issues I've had with the KVO implementation, kudos Mike!)

Please, no one say I shouldn't be writing a game with Objective-C; KVO is the 
only thing that's tripped me up speed-wise about it. (Well, that and the audio 
threads doing a heck of a lot of sound processing, I keep wondering if I can 
put my WAV files into some format that requires less CA conversion or whether 
it's NSSound forcing that on me...)

-- Gwynne

___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Re: Key-Value Observing speed

2010-03-12 Thread Gwynne Raskind
On Mar 12, 2010, at 4:52 PM, Peter Ammon wrote:
 While profiling a project I'm working on, I found that while most of my time 
 was being spent in glFlush() (which is completely expected for an 
 OpenGL-based game), a non-trivial amount of time is being spent in dozens of 
 KVO internal methods and functions. Most especially, I noticed that KVO (or 
 possibly the KVC beneath it) makes heavy use of NSInvocation-based 
 forwarding, which is known to be the slowest possible code path for message 
 dispatch.
 I think KVO only uses NSInvocation when setting or getting non-standard 
 aggregate types.  So if your property is any primitive C type, any ObjC 
 object, or an NSPoint, NSRect, NSRange, or NSSize, then it will not use 
 NSInvocation.  If it's a custom struct it will.  Does that seem plausible 
 based on what your property types are?
 
 If not, it would be helpful to post a backtrace for the call to 
 +[NSInvocation invocationWithMethodSignature:], so we can figure out what's 
 happening.


You're right; the specific call that's causing the worst speed issues is 
returning a property typed with this structure:

typedef struct { int32_t x, y; } IntegerPoint;

It's not necessarily feasible to switch this to an NSPoint; it means digging up 
every point in the code that relies on signed 32-bit integer math and doing 
manual typecasting (or calling lround()) away from CGFloat. If there's no way 
to cheat KVO into doing this sanely, I'll resign myself to it, but I kinda hope 
there's something a little less annoying.

(It's even more annoying because it *was* an NSPoint in a much earlier 
iteration of the code and I changed it because it simplified the code in two 
dozen places, and because the property in question is integer and doesn't need 
the slower floating-point instructions to manipulate it.)

-- Gwynne

___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Re: Key-Value Observing speed

2010-03-12 Thread Gwynne Raskind
On Mar 12, 2010, at 5:49 PM, Greg Parker wrote:
 You're right; the specific call that's causing the worst speed issues is 
 returning a property typed with this structure:
 
 typedef struct { int32_t x, y; } IntegerPoint;
 
 It's not necessarily feasible to switch this to an NSPoint; it means digging 
 up every point in the code that relies on signed 32-bit integer math and 
 doing manual typecasting (or calling lround()) away from CGFloat. If there's 
 no way to cheat KVO into doing this sanely, I'll resign myself to it, but I 
 kinda hope there's something a little less annoying.
 Perhaps you can pack it in and out of a 64-bit integer? KVO might handle 
 int64_t natively.

But then I'm back to changing every place in the code that looks at this 
property :).

On Mar 12, 2010, at 6:21 PM, Mike Abdullah wrote:
 What options are you using to observe this property? What if you have an 
 additional method you bind to that returns an IntegerPoint already wrapped up 
 in an NSValue or similar?


My options are 0; I don't need old or new values, or initial or prior 
notifications :). Is the cost of creating an autoreleased NSValue (there's a 
category on NSValue to wrap this struct, so that part's trivial at least) and 
extracting its value less than that of taking an NSInvocation? And that still 
doesn't solve taking apart the code :).

Lots of good ideas, but it sounds so far like my best bet is to just go back to 
an NSPoint, since it looks like I'll have to change everything in the code that 
uses it anyway.

-- Gwynne

___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Re: Key-Value Observing speed

2010-03-12 Thread Gwynne Raskind
On Mar 12, 2010, at 10:22 PM, Michael Ash wrote:
 You're right; the specific call that's causing the worst speed issues is 
 returning a property typed with this structure:
 
 typedef struct { int32_t x, y; } IntegerPoint;
 
 It's not necessarily feasible to switch this to an NSPoint; it means digging 
 up every point in the code that relies on signed 32-bit integer math and 
 doing manual typecasting (or calling lround()) away from CGFloat. If there's 
 no way to cheat KVO into doing this sanely, I'll resign myself to it, but I 
 kinda hope there's something a little less annoying.
 
 (It's even more annoying because it *was* an NSPoint in a much earlier 
 iteration of the code and I changed it because it simplified the code in two 
 dozen places, and because the property in question is integer and doesn't 
 need the slower floating-point instructions to manipulate it.)
 Implement +automaticallyNotifiesObserversForKey: to return NO for that
 key, then call will/didChangeValueForKey: yourself in the setter. That
 will avoid the expensive automatic KVO machinery, while allowing you
 to leave everything else untouched.


The key is already manually notified, but when I re-ran Instruments to 
double-check my results... Well, sigh. As people often seem to do with such 
things, I was misinterpreting what it was telling me. The CPU time's actually 
in -[NSView setNeedsDisplay:] for some reason. Sorry for the noise.

-- Gwynne

___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Re: Versioning / increasing build number

2010-02-05 Thread Gwynne Raskind
On Feb 5, 2010, at 1:56 PM, jonat...@mugginsoft.com wrote:
 2) Right now the file doesn't get built new every time I build my 
 application. So the number isn't increasing yet. How can this be achieved?
 I use the following in a script phase to get a perpetually increasing build 
 number.
 
 #!/bin/bash
 # http://davedelong.com/blog/2009/04/15/incrementing-build-numbers-xcode
 buildNumber=$(/usr/libexec/PlistBuddy -c Print MGSBuildNumber Info.plist)
 buildNumber=$(($buildNumber + 1))
 /usr/libexec/PlistBuddy -c Set :MGSBuildNumber $buildNumber Info.plist


This taints your original Info.plist with changing data, which is annoying for 
version-controlled code. You can find the script I use at 
http://blog.darkrainfall.org/?p=185; it's a short AppleScript that tricks 
Xcode into doing the right thing.

-- Gwynne

___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Re: Allow only root/admin users to execute the cocoa app

2010-01-24 Thread Gwynne Raskind
On Jan 25, 2010, at 1:47 AM, vincent habchi wrote:
 I want to allow my cocoa app to be only launched by root/admin users.
 How can i achieve this?
 As I think has already been mentioned, the UNIX approach is to set the 
 application's owner as root and then make it only executable by the owner. 
 However, Apple largely discourages programmers from developing Cocoa apps 
 that will be run with root privileges.
 I know that, but, up to this point, I have failed to find any reasonable 
 reason ;) that could justify this point of view, especially since it is 
 always possible to drop root privileges at whatever point, just like postfix 
 or named do. I don't see why being root is permissible for CLI apps and not 
 for GUI ones.

Because that's what the security model of OS X is built around. First and 
foremost, CLI programs have a much smaller attack surface than GUI apps, since 
they link to much less code and interact with much less of the system.

Secondly, separating your root code into another process limits the possible 
exploits, and the possible accidents, by quite a bit. You have less code to 
secure against privilege escalation attacks.

Thirdly, to my knowledge, AppKit assumes itself to be running as the user 
logged into the window server session it connected with at startup; having an 
euid of root might well cause several bits of Cocoa to behave wierdly or 
completely fail.

Fourthly, as Clark mentioned, code can be injected into running processes in a 
Mach system, which makes dropping privileges with seteuid(getuid()) completely 
useless - the injected code can just seteuid(0) and get root back from the 
saved-set-user-ID. And if you drop them with setuid(getuid()), you've lost 
access to the root privileges you wanted anyway, assuming an injected attack 
vector doesn't run before you make the call anyway.

Finally, in general it's good practice on any system (be it OS X, Windows, or 
any UNIX flavor) to run with as few privileges as you need at any given time. 
Security conscious users and the paranoid like myself are liable to kill a 
process that's running as root without a visible reason, most especially a GUI 
process doing so.

What exactly are you trying to do that requires running as root? You can verify 
that a user has an admin account with Authorization Services at startup, then 
use the same APIs to run a tool to do your root work as necessary. As Todd 
pointed out, Apple provides a very complete set of code for doing this in 
BetterAuthorizationSample.

-- Gwynne

___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Problem using bindings with deep key paths

2010-01-20 Thread Gwynne Raskind
This is most likely a very basic question, but I seem to be stumped just the 
same.

I have an application nib (MainMenu) set up such that it instantiates the 
NSApplication delegate and the application's main window.

The application delegate class has a property player. The player is an 
instance of a class Player, which has as a property track, which is 
(naturally enough) a Track object. Finally, the Track object has a property 
info, which is again obviously an Info object.

The Player object is effectively constant; from a KVO perspective, it never 
changes over the course of the application. The Track object it contains 
changes often, and therefore the Info changes as well.

I created an NSObjectController at the top level of the nib, and connected its 
content outlet to the application delegate. I then created a second 
NSObjectController, and bound its contentObject binding to selection.player 
on the first controller. Repeat inwards until there are four controllers, one 
for each level of the above-described model objects. (This is not the natural 
configuration, but rather one of the variants I tried in the process of trying 
to make this work. The original configuration was a single object controller 
bound to the app delegate.)

Finally, I bound several views' value bindings to the controller for the Info 
object, with the appropriate model keys for the Info class, one of which is the 
aptly-named title (not to be confused with Sir Not Appearing In This Film). 
The full key path for the NSTextField in question is 
selection.player.track.info.title, where selection is the app delegate.

It didn't work. The UI did not update with the values in the Info object for 
the given Track in the Player. I tried a couple dozen things, and finally found 
that the UI updated correctly when I generated a fake KVO notification for the 
player key in the application delegate.

It seems to me that this means that the object controller(s) are not observing 
the changes made to the various sub-objects of the application delegate. In 
other words, given the key path player.track.info.title, any change to any 
key along that path is ignored unless player is considered to have changed as 
well. I've verified that all the accessors are fully KVC and KVO compliant 
(most are synthesized properties), and I've tried a long list of combinations 
of flags on the controllers and individual bindings.

Is this a design failure on my part, or am I trying to do something that 
bindings can't handle? To summarize, I want my UI to update any time I change 
the current Track object, which is contained by the constant Player object. 
This all worked very nicely and very neatly when I was using outlets and doing 
the KVO bits myself; the only issue I had with it then was that there were a 
whole lot of outlets on the application delegate...

(Note: The documentation on bindings is quite ancient (some of the screenshots 
are from 10.3's IB, for mercy's sake) and was completely unhelpful.)

-- Gwynne

___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Re: Problem using bindings with deep key paths

2010-01-20 Thread Gwynne Raskind
On Jan 20, 2010, at 5:00 PM, Quincey Morris wrote:
 It didn't work. The UI did not update with the values in the Info object for 
 the given Track in the Player. I tried a couple dozen things, and finally 
 found that the UI updated correctly when I generated a fake KVO notification 
 for the player key in the application delegate.
 
 It seems to me that this means that the object controller(s) are not 
 observing the changes made to the various sub-objects of the application 
 delegate. In other words, given the key path player.track.info.title, any 
 change to any key along that path is ignored unless player is considered 
 to have changed as well. I've verified that all the accessors are fully KVC 
 and KVO compliant (most are synthesized properties), and I've tried a long 
 list of combinations of flags on the controllers and individual bindings.
 It seems to me that you've *proven* that one of the properties along that key 
 path is not being updated KVO compliantly, either in general or specifically 
 in the series of initializations related to nib loading. The idea of 
 suspecting the observers, while attractive in that it shifts the blame to 
 Cocoa, is not supported by the proven robustness of the bindings 
 implementation, so I'd put that thought way down your list. :)
 
 I'd suggest you try adding 4 user interface objects (for example, text fields 
 bound to player.description, player.track.description, 
 player.track.info.description and player.track.info.title, as model keys 
 of a single object controller) to find out which property is malfunctioning. 
 That will suggest which piece of code to examine for KVO-uncompliance, or 
 possibly for some other problem.
 
 Also, as usual, remember to check your console log for exception messages. 
 KVC/KVO has an annoying habit of running *nearly* correctly after an 
 exception, so it's easy to forget to check.


As usual, the blindingly obvious proves to be the problem. I had ensured 
perfect KVC/KVO compliance, and I was using the compliant accessors everywhere 
except for one place: the delegate's -awakeFromNib method where I create the 
Player object in the first place. I declared the property readwrite in the 
class extension and changed player = [[Player alloc] init] to self.player = 
[[[Player alloc] init] autorelease], and suddenly it all worked. (Though it 
vaguely annoys me that I have to add a spurious retain/autorelease to the 
Player object.)

Thanks for your help, Quincey; your suggestion of binding a series of text 
fields made the problem instantly obvious :).

-- Gwynne

___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Re: Problem using bindings with deep key paths

2010-01-20 Thread Gwynne Raskind
On Jan 20, 2010, at 6:05 PM, Quincey Morris wrote:
 (Though it vaguely annoys me that I have to add a spurious 
 retain/autorelease to the Player object.)
 You don't technically have to. You could do:
 
 [self willChangeValueForKey:@player];
 player = [[Player alloc] init];
 [self didChangeValueForKey:@player];
 ... which is unexceptionable, but another alternative might be:
 
   Player* aPlayer = [[Player alloc] init];
   self.player = aPlayer;
   [aPlayer release];
 
 although (given a couple of contemporaneous threads on the subject of 
 autorelease and its subtleties, and given that I'm sitting smugly on the GC 
 side of the fence) I wouldn't be surprised to find out that the latter 
 suggestion sucks.


I've gotten the idea (mostly from this list and objc-language) that GC is 
fraught with all manner of peril, and since my coding style is pedantic enough 
to keep me from most retain/release management mistakes (with the help of 
Clang's analyzer), I stick to what I know :). All three options are ugly in 
their own ways. In this specific case, since the Player object never changes, I 
could make the property assign instead of retain and manually release it in 
-dealloc, but I consider that equally ugly since it's conceptually incorrect 
(I'd be declaring the Player to be a weak reference when it isn't).

-- Gwynne

___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Re: My try/catch block isn't catching exceptions on 10.6

2009-11-28 Thread Gwynne Raskind
On Nov 28, 2009, at 4:25 AM, Greg Parker wrote:
 Here's a fun idiom for handling both C++ and Objective-C exceptions in the 
 same place (on iPhone and 64-bit Mac).
 
@try {
// do stuff
} @catch (NSException *e) {
// NSException
} @catch (id e) {
// Other Objective-C exception
} @catch (...) {
// Non-ObjC exception
// Decode it by rethrowing it inside a C++ try/catch.
try {
@throw;
} catch (std::bad_cast e) {
// C++ failed dynamic cast to reference type
} catch (...) {
// Other C++ exception
// or non-ObjC non-C++ foreign exception
}
}


I apologize if this is a dense question, but can't you just go like this?

   @try {
   // do stuff
   } @catch (NSException *e) {
   // NSException
   } @catch (id e) {
   // Other Objective-C exception
   } @catch (std::bad_cast e) {
   // C++ failed dynamic cast to reference type
   } @catch (...) {
   // Other C++ exception
   // or non-ObjC non-C++ foreign exception
   }

-- Gwynne

___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Is Core Data appropriate to my task?

2009-09-10 Thread Gwynne Raskind
I have an application that manages two kinds of data: A singular file  
that contains a large amount of rarely changed (but not invariant)  
data, and documents that contain one root object's worth of  
information that connects to the singular data set in a very large  
number of places; the documents are in fact little more than a chosen  
list of references into the singular data set, plus some small bits of  
independant data. The documents are modified quite often.


Originally I thought Core Data must surely be ideal for this sort of  
application; the object graph management alone should have been very  
helpful, to say nothing of the management of stores and the abilty to  
integrate with bindings and NSDocument. I got as far as reading all  
the basic (and some of the not so basic) Core Data documentation and  
began wondering whether or not my data would fit into its model after  
all. For example, in the large singular data set, there are a large  
number of what SQL would call lookup tables, data that's used only  
to avoid duplicating a set of constant values that are used elsewhere.


To use the Employee/Department example from the Core Data docs,  
sometime in the future an Employee might have a planetOfOrigin  
attribute. Assuming one limits one's self to the restriction of the  
speed of light (so, not TOO far in the future), the resulting Planet  
entity would only ever have a small number of possible values. Such an  
attribute might be better modeled in the Employee entity by something  
like SQL's ENUM or SET types. If the set of possible values is Earth  
and Not Earth, a Boolean might make more sense. If the set of  
possible values is Earth, Mars, Venus, etc., an ENUM would be a  
reasonably obvious choice; after all, how often does the solar system  
gain or lose a planet (cough Pluto cough)? With such a small data set,  
a lookup table would only be the obvious choice if the set of possible  
values was expected to change with any frequency. But Core Data has no  
support for such a thing; I would either have to write a custom  
property type or model it by creating the Planet entity and giving it  
a relationship from Employee.


Let's pretend the lookup table *was* the obvious choice for some  
reason; the speed of light barrier has been broken and now there's a  
whole mess of planets. So in Core Data parlance, the Employee entity  
has a one-to-one relationship to the Planet entity. The inverse  
relationship from Planet to Employee, all employees from this planet  
is technically feasible, even easy, to model, but it's almost  
certainly a waste of time and effort. But the Core Data documentation  
offers a long list of very dire warnings about one-way relationships  
between entities.


Worse, the list of possible Planets certainly doesn't belong in the  
same document file that holds a single Employee's data; you'd end up  
duplicating that data across every single Employee. So the list of  
Planets would instead be in a global store. But oops, Core Data can't  
model cross-store relationships, so you use a fetched property, which  
is one-way. Inverse relationship problem solved, unless you actually  
had a use for that relationship. But fetched properties need a fetch  
request, and what do you put in the predicate? Now you need some kind  
of identifier in the Employee for the fetch to operate on, and now you  
have two fields (the planetOfOriginName string for the predicate and  
planetOfOrigin as the fetched property) to model a single  
relationship. How to maintain referential integrity? And what if you  
DID want the inverse relationship - do you model another fetched  
property in the other direction? What's the predicate there,  
planetOfOriginName LIKE [c] $FETCH_SOURCE.name? Now your Planet  
entity has intimate knowledge of the structure of your Employee  
entity; that can't be good.


It seems to me that Core Data really is intended to deal with lists of  
root objects, i.e. the entire list of Employees in one store, rather  
than one Employee per store. The Core Data documentation mentions  
attaching multiple stores to a persistent store coordinator, but I  
can't make any sense of how interrelationships between the stores are  
handled.


Is Core Data really more appropriate to my dataset than an SQLite  
database and a simple Employee object that fetches from that database?  
If so, I'd appreciate some help in understanding how.


(Let me take this opportunity to say that for all the warnings that  
Core Data is not and never has been a database, almost every concept I  
see in it makes me think O/R mapper for SQLite.)


-- Gwynne

___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:

Re: Is Core Data appropriate to my task?

2009-09-10 Thread Gwynne Raskind

On Sep 10, 2009, at 3:21 PM, Erik Buck wrote:
Yes.  Use Core Data.  Your application is exactly what Core data is  
intended to support.


Create a planet entity.
Create a one to many relationship so that each employee has one  
planet, but each planet has an unlimited number of employees.


This is exactly what lookup tables in sql produce.  There is no  
need for fancy fetched properties.  There is no problem with having  
planet entity instances in the same store with employee entity  
instances.  It is a good design that makes your data stores self  
sufficient.  There will only be one instance of the planet entity  
for each planet that you define.  Right now, you would never have  
more than 8 or 9 planet entity instances no matter how many employee  
instances you have.


You could also just have a planet of origin string property in  
each Employee entity.  The property could default to Earth.  There  
is no need for a custom Enum type when strings work perfectly  
well.  You can even validate the strings whenever they change to  
restrict the set of valid strings.  Constant strings will tend to  
have the same pointer, so you won't even have the cost of separate  
string copies for each Employee instance.



I don't see this as being equivelant at all.

Extending the example, let's say the company with these Employees has  
as its directors several discriminating unfair people, and thus an  
Employee from any given Planet gets a salary adjustment based on that  
Planet. The obvious place for this data is the Planets table, or in  
Core Data's case, the Planet entity. A salaryAdj column (attribute)  
is added to the Planets table (Planet entity) and filled in with the  
(in)appropriate numbers.


Now suddenly the company is taken over by far more benevolent and  
considerate people, whose only flaw is that they don't want to break a  
system that works by removing an entire column from a database table  
(a schema change is much more difficult than a data update, after  
all), so they just UPDATE Planets SET salaryAdj=0.


So someone loads up an Employee whose Planet instances are in the same  
store with that Employee, and the old salary adjustment is still  
sitting there in the saved data. I sense unhappy Employees in this  
company's future. If only the coder who wrote the payroll system had  
put the Planet data in some global store where changes to it would  
propogate correctly to all Employees.


Does Core Data still solve the problem? Is there some reason that  
using Core Data for everything would be better than storing the global  
rarely-updated data in a real database and using Core Data only for  
the Employee entity, which is the only part which really talks to the  
UI anyway? (Something tells me the key point is right there...) For  
that matter, if Core Data is only managing one entity, what's the use  
of Core Data at all? With all the data being referential between the  
database and the entity, just define a simple NSObject subclass which  
contains a few instance variables and implements NSCoding.


-- Gwynne

___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Re: Is Core Data appropriate to my task?

2009-09-10 Thread Gwynne Raskind
Before anything else, let me say thank you for a clear, concise, and  
very helpful set of answers to my questions; I was expecting rather  
more of a struggle for understanding :).


On Sep 10, 2009, at 5:04 PM, Ben Trumbull wrote:

support for such a thing; I would either have to write a custom
property type or model it by creating the Planet entity and giving it
a relationship from Employee.
Correct.  You can write a custom NSValueTransformer with the  
Transformable property type to implement an ENUM, or normalize the  
data into a separate table as a formally modeled entity.  Which is  
better depends on how big the data values are, how many of them  
there are, and how frequently they change.


Is that really so bad ?  The alternative is to do ALL the work  
yourself.


Mostly I just wanted to be certain that there was nothing obvious I  
was missing :).



The inverse
relationship from Planet to Employee, all employees from this  
planet

is technically feasible, even easy, to model, but it's almost
certainly a waste of time and effort. But the Core Data documentation
offers a long list of very dire warnings about one-way relationships
between entities.
Yes, and for most situations those warnings are there for very good  
reasons.  But if there were no reasons for such relationships, then  
it wouldn't be a warning, it simply wouldn't exist.


The manual isn't at all clear about this, but if I understand  
correctly, you're basically saying, Though it is almost always  
technically possible to model an inverse to any relationship, there  
are sometimes circumstances in which it is correct not to do so. Is  
that accurate, and if so, should I file a documentation bug requesting  
clarification on that and the circumstances in which it's true?



Worse, the list of possible Planets certainly doesn't belong in the
same document file that holds a single Employee's data; you'd end up
duplicating that data across every single Employee. So the list of
Planets would instead be in a global store.
There are lots of ways to model that, but, yes, this would be the  
most natural.


I can't think of any others offhand, but I haven't worked with this  
sort of data before; could you give some examples?



But oops, Core Data can't
model cross-store relationships, so you use a fetched property, which
is one-way.
You could use a fetched property, or handle this in code by storing  
a URI for the destination object in a different store, and fetching  
the matching objectID either lazily in in -awakeFromFetch.  We've  
generally recommended using a custom accessor method for this  
instead of fetched properties.


Is there any particular reason for that recommendation? The  
documentation explicitly recommends fetched properties for cross-store  
relationships (one instance of several is in the Core Data Programming  
Guide, Relationships and Fetched Properties chapter, Fetched  
Properties section, first paragraph, where it says  In general,  
fetched properties are best suited to modeling cross-store  
relationships...)


Also, if you do in code or fetched properties, this hand made cross  
store relationship, you should prefer numeric keys to text strings  
for your joins.  Creating a de facto join through a LIKE query is  
pretty crazy.  That's a case insensitive, local aware, Unicode regex  
there.  String operations are much more expensive than integer  
comparisons.  At the very least, use == for your string compares.


Don't worry, I already had the experience of having to work with a  
codebase that used string keys as its only cross-table links in mSQL.  
Eventually we had to recreate the whole system from scratch.


It seems to me that Core Data really is intended to deal with lists  
of

root objects, i.e. the entire list of Employees in one store, rather
than one Employee per store.
One document per Employee is a bit unusual.  But it's feasible if  
that's your requirement.


Employee was just the example I yanked out of the Core Data docs :). A  
better analogy would be the Picture example. If you use Core Data  
entities to store the various elements of a vector graphic, you would  
certainly want to be able to store one graphic per document.



(Let me take this opportunity to say that for all the warnings that
Core Data is not and never has been a database, almost every  
concept I

see in it makes me think O/R mapper for SQLite.)
Core Data is an O/R mapping framework, among other things.  But O/R  
frameworks are not SQL databases.  Modeling your data in any O/R  
framework as if you were writing SQL directly is inefficient and  
mistaken.


Saying that Core Data is a database is like saying your compiler is  
an assembler.  Well, the compiler suite uses an assembler, sure, and  
they both output object code in the end, but that does not mean the  
best way to use your compiler is to write in assembly.



Nonetheless, Core Data does manage the data stored on disk as well as  
the representation of 

Re: How determine if file is in Trash, given Path or Alias

2009-06-01 Thread Gwynne Raskind

On Jun 1, 2009, at 4:31 PM, Sean McBride wrote:

This is a nice trick, I wasn't aware of that function, thanks.
Perhaps a minor improvement (one call instead of two):

- (BOOL) isTrashedFileAtPath:(NSString*)path
{
Boolean inTrash = false;
const UInt8* utfPath = (UInt8*)[path UTF8String];
OSStatus err = DetermineIfPathIsEnclosedByFolder(kOnAppropriateDisk,
kTrashFolderType, utfPath, false, inTrash);
return (noErr == err) ? (true == inTrash) : NO;
}

Probably it does the same thing behind the scenes, but why not.

For the archives: 2 more problems:

a) use fileSystemRepresentation not UTF8String.

b) with GC, 'path' may be collected before
DetermineIfPathIsEnclosedByFolder() is finished with utfPath.  So best
to add a [path self] just before the 'return'.



This is a perfect example of why I would never use GC: That is the  
most nonintuitive confusing behavior I have ever heard of. If I  
crashed in the middle of DetermineIfPathIsEnclosedByFolder() for that  
reason I would never guess that GC was responsible!


-- Gwynne

___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Re: Several Questions

2009-05-31 Thread Gwynne Raskind

On May 31, 2009, at 2:08 PM, Ammar Ibrahim wrote:

Can you give us so more details? For example: What will the app do?
Your description is very strange, lol.

But indeed, you should create a normal cocoa app that do the stuff  
you

want to do (UI + the real stuff),
and a little daemon that checks every X minutes if the other app is
running:
  yes: ok, continue
  no: start app (log message? App was stopped)

Look at CFNotification and the distributed notification center (I  
thought
there was a Cocoa variant of that, but I can't seem to find it) for  
a way to
detect whether your app has hung. You could just do a ping/pong set  
of
question/reply notifications that your daemon sends to your app and  
gets a
reply. If the app is still running but there's no reply within a  
sensible

timeframe, something has gone wrong.

This seems like a very doable approach. Anyhow, the daemon itself  
might

crash, so I would go for a cron job that runs say every 5 mins,

Now let's assume the app was running and not responding, I couldn't  
find any
API to force quit another application. Would a `kill -9 {process  
ID}` be

sufficient?


The Cocoa variant of the distributed notification is  
NSDistributedNotificationCenter :).


kill -9 {process ID} is shell-ese for the POSIX call kill(2) with a  
parameter of SIGKILL:


NAME
 kill -- send signal to a process

SYNOPSIS
 #include signal.h

 int
 kill(pid_t pid, int sig);

The rest of the manpage has more info if you need it.

Note that OS X's Force Quit command doesn't send SIGKILL immediately;  
I believe it sends SIGINT and SIGQUIT before resorting to SIGKILL,  
since a process can trap SIGINT and SIGQUIT, use them to perform  
emergency cleanup before dying, or even just ignore them completely.  
SIGKILL can not be trapped, caught, ignored, or otherwise stopped from  
terminating the process.


-- Gwynne

___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Re: Showing more warnings possible in Xcode?

2009-05-30 Thread Gwynne Raskind

On May 30, 2009, at 9:11 PM, Alex Curylo wrote:

You also have the unused attribute:
http://gcc.gnu.org/onlinedocs/gcc-3.1.1/gcc/Variable-Attributes.html
That's out because I commonly have to share code with Windows  
compilers.


... although much less commonly now that I'm about 80% focused on  
iPhone work, which makes being so even *more* joyous!



Not to mention I haven't yet figured out a way to apply  
__attribute__((unused)) to an ObjC method parameter. I just get a pile  
of syntax errors, or it gets applied to the function instead of the  
parameters.


-- Gwynne

___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Re: Showing more warnings possible in Xcode?

2009-05-29 Thread Gwynne Raskind

On May 29, 2009, at 11:22 PM, Graham Cox wrote:
Is there a way to tune xCode so that it warns you of these types of  
potential problems (and more)?  The Java development environment  
I've been using for the past several years (Jetbrains IDEA) has  
unbelievably fantastic code-editing and compile-time warning  
systems that allow you to show a myriad of situations as warnings  
(some are user definable).  Is there a way to do this in xCode, or  
at least set some flags to get more verbose warnings (especially  
those that can prevent dumb mistakes)?
In your project's build settings, scroll down to Other Warning  
Flags, and paste this lot in:


-Wall -Wcast-align -Wchar-subscripts -Wextra -Wextra-tokens - 
Wformat=2 -Wmissing-field-initializers -Wpointer-arith -Wshadow - 
Wswitch-default -Wundef -Wwrite-strings


I'm not immediately sure what they all do, but that's what I compile  
with (cleanly).



Nice list, Graham :).

It's important to note that the original question, warning about  
uninitialized automatic variables, is only possible in GCC when  
optimization is turned on. From Xcode's research assistant for that  
particular setting (emphasis mine):


--
Warn if a variable might be clobbered by a setjmp call or if an  
automatic variable is used without prior initialization.


***Detection of uninitialized automatic variable requires data flow  
analsys that is only enabled during optimized compilation.***


Note that GCC cannot detect all cases where an automatic variable is  
initialized or all usage patterns that may lead to use prior to  
initialization.

--

In short, you can't get this warning in a Debug-style build unless you  
want to sabotage your debugging efforts by adding optimization.


-- Gwynne

___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Re: which temp dir to use?

2009-05-25 Thread Gwynne Raskind

On May 25, 2009, at 6:52 PM, Michael Ash wrote:

The authentication stuff is pertinent, because the AEWP is an example
of an API which works by having an unprivileged user process
communicate with a privileged process that does the work. A technique
which allows you to compromise a process which uses AEWP demonstrates
how this compromise can be done with any such setup, even using a
secure channel (which AEWP does).


It does? Last I checked, AEWP() used a temp file on disk to pass its  
AuthorizationRef to the child process. Pipes, anyone?


-- Gwynne, Daughter of the Code
This whole world is an asylum for the incurable.

___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Re: dot notation doesn’t work as expected f or some library classes

2009-05-24 Thread Gwynne Raskind

On May 24, 2009, at 6:00 PM, Marc Liyanage wrote:
I was playing around a bit with the Obj-C 2.0 dot notation to  
clarify some things for me. In my own classes getters and setters  
are called as expected, but I noticed several times already that  
library classes sometimes don’t allow the dot notation (that’s the  
reason why I’m trying to clarify this in the first place).



I’m wondering why this example with NSMutableString does not compile:

#import Foundation/Foundation.h

int main (int argc, const char * argv[]) {
   NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

   NSMutableString *xyz = [NSMutableString string];
   xyz.string = @foo;

   [pool drain];
   return 0;
}


This fails to build with the message error: request for member  
'string' in something not a structure or union. That message is  
expected when there is no such accessor, but it does compile when I  
replace the dot notation accessor with this:


[xyz setString:@foo];

This should be exactly the same. I can’t see how this could behave  
like it does when the dot notation is simply syntactic sugar, as the  
documentation states.



My first guess: The class isn't KVC compliant, or more to the point  
there's no corresponding -string method. The compiler seems to need  
KVC compliance to use property syntax, even though it's not actually  
using KVC.


-- Gwynne, Daughter of the Code
This whole world is an asylum for the 
incurable.___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Properly scaling a vector image with CG

2009-05-24 Thread Gwynne Raskind
I have a UIView inside a UIScrollView. The UIView has a bunch of  
CALayers with custom drawing code which render vector images. A nice  
thing about vector images is that when you zoom in on them, they still  
look good. But using UIScrollView's zooming support, I still get nasty  
bitmap zooming - because UIScrollView is setting the transform  
property of my view, which is transforming the contents of the view  
without redrawing them. How can I manipulate the scaling so that my  
drawing code can scale the drawing properly? I'm okay with it looking  
blocky during the zoom animation, as long as it redraws prettily when  
the zoom is done.


The only solution I can see right now is to track the user's zoom  
gesture by hand and manipulate my view's bounds, scroll view's content  
size, and layer scaling values by hand. This seems like a very ugly  
solution which duplicates a lot of effort that UIScrollView puts in  
for me.


Any thoughts? Any help is appreciated.

-- Gwynne, Daughter of the Code
This whole world is an asylum for the incurable.



___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Re: isKindOfClass returns null instead of YES or NO

2009-05-21 Thread Gwynne Raskind

On May 21, 2009, at 12:33 PM, Sean McBride wrote:

NSLog(@Is Member of NSURL: %@, [[step class] isMemberOfClass:
[NSURL class]]);

The %@ placeholder is for arguments that are objects.
isMemberOfClass: and isKindOfClass: return a BOOL, which is not an
object.

Jeff,

And if you're wondering if the compiler could warn you that %@ and  
BOOL
do not match, the answer is unfortunately no.  -Wformat=2 can give  
such

warnings when using sprintf() and friends, but not NSString methods.
One of my pet peeves. :)



Interestingly enough, if you pop over to:

http://www.opensource.apple.com/source/gcc_42/gcc_42-5531/gcc/c-format.c

You will find that Apple has indeed dropped in -Wformat checks for  
nsstring_format_type and cfstring_format_type. But if you scroll  
down a ways further, you'll find that OOPS!, Apple hasn't actually  
implemented those types, at least not completely. One wonders why. Bug  
filing time, anyone?


-- Gwynne, Daughter of the Code
This whole world is an asylum for the incurable.



___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Re: Controlling some of CoreAnimation's more confusing automation

2009-05-21 Thread Gwynne Raskind

On May 21, 2009, at 1:09 PM, David Duncan wrote:
I have a UIView that contains a number of CALayers. Nothing unusual  
here. The CALayers are subclassed to do their drawing, because that  
was easier than separating the delegate logic from my UIView  
subclass (since the view can't be the delegate of a sublayer - it  
causes an infinite recursion to do so, why isn't there a check for  
this somewhere in CA's or Cocoa Touch's code?).
UIKit expects that a view and layer are tightly coupled and that the  
view is not a shared delegate between multiple layers, period. Even  
if it worked, you would see a lot of behavior that you may not  
desire by setting a view as a layer's delegate.


My question, though, is why isn't there an assert somewhere in the CA  
or UIView logic that says WARNING, WARNING, YOU'VE DONE SOMETHING  
BAD!!! Throw an exception or something! :)


1) animate the custom properties more directly with a  
CABasicAnimation. I tried this, but it did nothing at all.
Custom property animation is not supported on iPhone OS 2.x or Mac  
OS X 10.5.


Well, here's hoping for that support in a future release.

2) get some control over the implicit animation CA is setting up  
for the contents transition. CATransaction only lets me set  
duration and the is enabled flag, whereas CAMediaTiming has a  
whole pile of useful parameters.
You can change the default animation for any property of a layer.  
See the documentation for -actionForKey: for more information.


Ah ha! This is what I was looking for, thanks!

-- Gwynne, Daughter of the Code
This whole world is an asylum for the incurable.



___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Controlling some of CoreAnimation's more confusing automation

2009-05-20 Thread Gwynne Raskind
I have a UIView that contains a number of CALayers. Nothing unusual  
here. The CALayers are subclassed to do their drawing, because that  
was easier than separating the delegate logic from my UIView subclass  
(since the view can't be the delegate of a sublayer - it causes an  
infinite recursion to do so, why isn't there a check for this  
somewhere in CA's or Cocoa Touch's code?).


Each time I call [anInstanceOfCALayer setNeedsDisplay], to update  
changes I've made to the layer's custom properties, Core Animation  
performs an implicit animation from the old cached data to the new  
draw state. For example, if I change a property so that my drawing  
code fills a path that was previously empty, the UI shows the filled  
space fading into existence.


I've figured out that I can explicitly disable this using the  
CATransaction calls wrapped around my call to -setNeedsDisplay. But  
I'd like to either:


1) animate the custom properties more directly with a  
CABasicAnimation. I tried this, but it did nothing at all.


2) get some control over the implicit animation CA is setting up for  
the contents transition. CATransaction only lets me set duration and  
the is enabled flag, whereas CAMediaTiming has a whole pile of  
useful parameters.


Any help would be appreciated.

-- Gwynne, Daughter of the Code
This whole world is an asylum for the incurable.



___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Re: When init returns nil does it cause a leak

2009-05-19 Thread Gwynne Raskind

On May 19, 2009, at 2:15 PM, Jesper Storm Bache wrote:
In the obj-c world we then have to implement classes to be able to  
handle a dealloc call before the initializer has completely executed.


My 2 cents...

If we aren't implementing our classes this way to begin with, then  
we're not programming our Objective-C correctly at all. As far as I'm  
concerned, dealloc should be able to handle a partially initialized  
object should be a language requirement. If any of Apple's classes  
don't handle this case properly, then it's a bug that should be filed.


-- Gwynne, Daughter of the Code
This whole world is an asylum for the incurable.
___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Re: Distinguish Pending Text from Committed Text

2009-05-19 Thread Gwynne Raskind

On May 19, 2009, at 10:35 PM, Dong Feng wrote:

Thanks Michael and Gideon's reply. [NSTextInput markedRange] works.

A minor question is that [NSWindow fieldEditor] returns an NSText*,
rather than an NSTextView*. I think that's because of historical
reason and it should be safe to always cast a returned NSText point to
an NSTextView. Is it safe?


I don't know if it's safe 100% of the time, but if you do it, drop an  
assert in your code for sanity's sake:


NSAssert( [returnedFieldEditor isKindOfClass:[NSTextView class]] ==  
YES, @Field editor is, in fact, an NSTextView. );


-- Gwynne, Daughter of the Code
This whole world is an asylum for the incurable.
___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Re: iPhone Generating and displaying images using Bitmap

2009-05-18 Thread Gwynne Raskind

On May 18, 2009, at 4:03 AM, Shraddha Karwan wrote:
I have a buffer containing JPEG image data. I need to display this  
buffer in
form of images. I copied this buffer to a file and then used the  
following:


CGDataProviderRef ref = CGDataProviderCreateWithFilename([appFile
UTF8String]);
CGImageRef imgRef =
CGImageCreateWithJPEGDataProvider 
(ref,NULL,YES,kCGRenderingIntentSaturation);

UIImage *theImage = [[UIImage alloc] initWithCGImage:imgRef];

Then displaying the image.
For some images I get the images but for some I get the JPEG Image  
corrupt

error message.
When I test the same data with Windows application it is able to  
display the

image without any error.
Is my conversion from JPEG buffer to UIImage file appropriate or am I
missing out some thing?


Wouldn't:

UIImage *theImage = [[UIImage alloc]  
initWithData:theJPEGDataBufferInMemory];


Be simpler and more effective?

That being said, your code looks correct. Can you give us the exact  
error message you get?


-- Gwynne, Daughter of the Code
This whole world is an asylum for the incurable.

___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Re: Creating NSAttributedString objects using WebKit in secondary thread

2009-05-11 Thread Gwynne Raskind

On May 11, 2009, at 7:42 PM, Dragan Milić wrote:
So, I assume creating attributed strings is not thread safe, but I  
don't
remember anything like that stated in the documentation. In my  
opinion, that

looks like a bug.

It is thread safe... if you stick to the Foundation methods. The
method you're trying to use, however, is part of the AppKit  
additions.

Hence the non-thread safeness.

One way to do this might be to spawn a helper app that accepts data
somehow (mach ports might be fastest using vm copy-on-write  
techniques

IIRC, but harder to implement), render on that process's main thread,
and then pass the data back (NSAttributedString supports NSCoding).
Would I necessarily need another helper app? Can I fork another  
(child) process and implement server side in it, which would  
receive raw bytes and return encoded attributed strings, and  
subsequently implement client side in the parent process (in its  
secondary thread), which would send raw bytes and receive back  
encoded attributed strings?


This is workable, but make sure you use a fork()/exec() pair to re- 
execute yourself in that case, and use argc/argv in your main() to  
determine which mode to run in. Don't just use fork() by itself -  
there are severe limits to what you can do in an only-fork()ed  
process. What those limits are isn't entirely clear to me; perhaps  
someone else could elaborate on that?


-- Gwynne, Daughter of the Code
This whole world is an asylum for the incurable.

___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Re: Hex to NSString or NSData

2009-05-09 Thread Gwynne Raskind

On May 8, 2009, at 11:34 PM, Mr. Gecko wrote:

And how could that make @68656c6c6f into @hello?

Thinking this will help you understand what I'm trying to do...

On May 8, 2009, at 10:23 PM, Jerry Krinock wrote:

On 2009 May 08, at 20:16, Mr. Gecko wrote:
Hello, I have a string with hex and I want to ether make it into a  
NSData or NSString. How might I do that.

-[NSString initWithBytes:length:encoding:]


If you need to scan 32-bit or 64-bit hex numbers, check out:

http://developer.apple.com/DOCUMENTATION/Cocoa/Reference/Foundation/Classes/NSScanner_Class/Reference/Reference.html 



DISCLAIMER: ALL CODE WRITTEN IN MAIL AND UNTESTED (Well, that's not  
quite true, I did test the long hex string function out of  
curiosity :) ).


Also note: All this code does simplistic error handling by throwing  
exceptions. You may want to just return nils or zeroes on failure.


- (uint32_t)unsignedIntFromHexString:(NSString *)str
{
NSScanner *scanner = [NSScanner scannerWithString:str];
uint32_t  result = 0;

if (![scanner scanHexInt:result])
{
		[NSException raise:NSInvalidArgumentException format:@No hex number  
found in %...@., str];

}
return result;
}
- (uint64_t)unsignedLongLongFromHexString:(NSString *)str
{
NSScanner *scanner = [NSScanner scannerWithString:str];
uint64_t  result = 0;
if (![scanner scanHexLongLong:result])
{
		[NSException raise:NSInvalidArgumentException format:@No hex number  
found in %...@., str];

}
return result;
}

If you need to scan arbitarily-sized hex strings, you'll need  
something more complex:


char hexCharToNibble(char nibble)
{
// 0 - 9
if (nibble = '0'  nibble = '9')
return (nibble - '0')  0x0F;
// A - F
else if (nibble = 'A'  nibble = 'F')
return (nibble - 'A' + 10)  0x0F;
// a - f
else if (nibble = 'a'  nibble = 'f')
return (nibble - 'a' + 10)  0x0F;
// Not a hex digit
else
		[NSException raise:NSInvalidArgumentException format:@Character %c  
not a hex digit., nibble];

return 0; // keep compiler happy
}

char hexCharsToByte(char highNibble, char lowNibble)
{
return (hexCharToNibble(highNibble)  4) | hexCharToNibble(lowNibble);
}

- (NSString *)interpretHexString:(NSString *)str asEncoding: 
(NSStringEncoding)encoding

{
	// Get the ASCII data out of the string - hexadecimal numbers are  
expressed in pure ASCII
	NSData	*asciiData = [str dataUsingEncoding:NSASCIIStringEncoding  
allowLossyConversion:YES];
	const char *chars = (char *)[asciiData bytes]; // chars is NOT NULL- 
terminated!


if (([asciiData length] % 2) != 0)
{
// There were an odd number of hex characters in the source 
string.
return nil;
}

// Set up data storage for the raw bytes we interpret
	NSMutableData *dataInEncoding = [NSMutableData dataWithLength: 
[asciiData length] / 2];

char*dataChars = [dataInEncoding mutableBytes];

// Loop over the ASCII numbers
for (NSUInteger i = 0; i  [asciiData length]; i += 2)
{
// Interpret each pair of hexadecimal characters into a byte.
*dataChars++ = hexCharsToByte(chars[i], chars[i + 1]);
}
	// Create an NSString from the interpreted bytes, using the passed  
encoding.
	// NSString will return nil (or throw an exception) if the bytes we  
parsed can't be

// represented in the given encoding.
	return [[[NSString alloc] initWithData:dataInEncoding  
encoding:encoding] autorelease];

}

It's very likely there's a faster/better/cleaner/whatever way to do  
this, but this does work :).


-- Gwynne, Daughter of the Code
This whole world is an asylum for the incurable.
___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Re: Hex to NSString or NSData

2009-05-09 Thread Gwynne Raskind

On May 9, 2009, at 5:20 PM, Marcel Weiher wrote:

int hexDigitToInt(char d)
{
  int result;
  switch (d) {
  case '0': result = 0; break;
  case '1': result = 1; break;
[snip]
  case 'E': result = 14; break;
  case 'F': result = 15; break;

  default:
  result = 0xFF;
  }

  return result;
}
Although it might look ugly, this is one of the fasted methods  
using standard C that converts a hex digit (nibble) to an int (2  
machine instructions).
OK, how do you get it to compile to just two instructions?  I've  
been looking at various optimization options, and as far as I can  
tell it is at least doing the following (non-contiguous):


1e67subl$0x30,%eax
1e6dcmpl$0x36,%eax
1e70jal 0x1f67
1e76movl0x0038(%ebx,%eax,4),%eax
1e7daddl%ebx,%eax
1e7fjmp *%eax

So that's 6 instructions to set up and perform the indexed jump to  
which the switch/case is being compiled.


At the jump sites, typically another 2 instructions:

1f60movl$0x000f,%eax
1f65jmp 0x1fd2

So that's a total of 8 instructions, with 2 taken and one typically  
non-taken jump and one of the taken jumps computed, so probably not  
predictable.  I must be missing something obvious.


The smallest (and likely fastest) would probably be the lookup table  
version:


char hexCharToNibbleL(char nibble)
{
const char lt[255] = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,  
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,  
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,  
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,  
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x01,  
0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0xFF, 0xFF, 0xFF,  
0xFF, 0xFF, 0xFF, 0xFF, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0xFF,  
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,  
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,  
0xFF, 0xFF, 0xFF, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0xFF, 0xFF,  
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,  
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,  
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,  
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,  
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,  
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,  
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,  
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,  
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,  
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,  
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,  
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,  
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,  
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF };

return lt[nibble];
}

This compiles down to (gcc 4.0, -Os, i386 arch):
_hexCharToNibbleL:
1b6epushl   %ebp
1b6fcalll   0x1b74
1b74popl%ecx
1b75movl%esp,%ebp
1b77subl$0x08,%esp
1b7amovsbl  0x08(%ebp),%eax
1b7emovsbl  0x038c(%ecx,%eax),%eax
1b86leave
1b87ret

My original if-elseif-elseif version, minus the exception raising,  
compiles down to:

_hexCharToNibble:
282dpushl   %ebp
282emovl%esp,%ebp
2830movzbl  0x08(%ebp),%edx
2834leal0xd0(%edx),%eax
2837cmpb$0x09,%al
2839jbe 0x2856
283bleal0xbf(%edx),%eax
283ecmpb$0x05,%al
2840ja  0x2847
2842leal0xc9(%edx),%eax
2845jmp 0x2856
2847leal0x9f(%edx),%eax
284amovl$0x,%ecx
284fcmpb$0x05,%al
2851ja  0x285b
2853leal0xa9(%edx),%eax
2856movl%eax,%ecx
2858andl$0x0f,%ecx
285bleave
285cmovl%ecx,%eax
285eret

And the switch-case version compiles to three pages of assembly full  
of addls, addbs, hlts, jmps, and so forth.


I ran some (very) simple benchmarks (full source code at the end of  
this message).


Examination of the assembly GCC produced for the code shows that gcc  
inlined the functions inside the for loops when optimization was  
turned on (both -O3 and -Os). The results are at the end of this  
message, after the source code.


Some conclusions:
 - Unoptimized, all three versions perform more or less the same:  
very slowly. This was pretty much a guarantee due to the overhead of  
all those uninlined function calls. But I tried forcing GCC to inline  
the functions, but it didn't help 

Re: Hex to NSString or NSData

2009-05-09 Thread Gwynne Raskind

On May 9, 2009, at 9:19 PM, Greg Guerin wrote:

char hexCharToNibbleL(char nibble)

Is safer as:
 char hexCharToNibbleL(unsigned char nibble)

Otherwise consider what happens if 'char' is signed by default and  
the incoming value is 0xB0.

const char lt[255] =

Should be:
 const char lt[256]

or:
 const char lt[]

and append another:
 , 0xFF

Otherwise the input value 0xFF will return an unspecified value.


You know, I knew somewhere in my brain that I was off by one there...  
but I generated the lookup table with a quickie PHP script and just  
accepted it when the compiler said I had too many initializers.  
That'll teach me :).



   return (nibble - '0')  0x0F;
The  0x0F is superfluous; you've already range-qualified the value  
of 'nibble', so subtracting '0' can't possibly yield anything other  
than 0-9.


Ditto for other uses of  0x0F.


True that... I'm just paranoid, I guess.


  c = hexCharToNibble(i % 255);
May want to use the  operator instead of %.  IIRC, modulus needs  
integer division, and may be taking more time than the inlined  
hexCharToNibble.


Yeah, but since that was only done as part of a benchmark, it didn't  
much matter. It may have skewed the numbers upwards unnecessarily, but  
wouldn't have changed their relation to each other since the same  
sequence was calculated for all three versions.


-- Gwynne, Daughter of the Code
This whole world is an asylum for the incurable.
___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Re: Hex to NSString or NSData

2009-05-09 Thread Gwynne Raskind

On May 9, 2009, at 10:20 PM, Greg Guerin wrote:
Yeah, but since that was only done as part of a benchmark, it  
didn't much matter. It may have skewed the numbers upwards  
unnecessarily, but wouldn't have changed their relation to each  
other since the same sequence was calculated for all three versions.
It changes the validity of terms like by a factor of about two  
because you haven't accounted for the overhead costs properly.  The  
overall times differ by a factor of two, but the code under test may  
not be faster by a factor of two.


Given the data:
 t(overhead) + t(c1) = t1
 t(overhead) + t(c2) = t1/2

This does not imply t(c1) equals t(c2)/2, unless t(overhead) is 0.

The % may still not matter much, but you can't infer it from the  
reported data.


Can you suggest a means to account for the overhead? I used i % 255  
because passing a constant value to any of these functions would only  
have tested a single code path in the switch and if-else forms. (It's  
worth noting that there IS only one code path in the lookup table  
form, i.e. there are no branches, which offers one explanation for its  
speed.) I could have passed i by itself without the modulus, but I  
wasn't sure off the top of my head whether that would exercise all the  
code paths either :).


-- Gwynne, Daughter of the Code
This whole world is an asylum for the incurable.
___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Re: iPhone how to suppress phone dialer screen

2009-05-08 Thread Gwynne Raskind

On May 8, 2009, at 7:35 AM, Shraddha Karwan wrote:

Hi,

I am writing an application which is in landscape mode. It dials a  
phone
number using the tel protocol. While dialing the standard iPhone  
dialer
screen pops up. Is there any means by which this screen can be  
suppressed?

Or how can I make this screen device orientation aware?
Is there any other means by which the same can be achieved without  
using the

tel protocol?


Please don't suppress the standard dialer screen. As long as it  
remains, the user has no doubt about what you're doing, and how to  
interact with the interface.


It would worry me if there *was* a way to suppress it. Control of the  
device belongs to the user, and providing a single funnel interface  
(the tel: protocol and its associated UI) to the dialing system brings  
us one step closer to assuring that.


-- Gwynne, Daughter of the Code
This whole world is an asylum for the incurable.

___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Re: iPhone Telephone APIs

2009-05-08 Thread Gwynne Raskind

On May 8, 2009, at 1:03 PM, Luke the Hiesterman wrote:

On May 8, 2009, at 10:00 AM, we...@mindspring.com wrote:
If you feel strongly (like I do) that this functionality should be  
made available, file a bug.  I'm thinking there is a legal reason  
this feature is not enabled, but I am unable to confirm my  
suspicions.
Why do you feel you should be able to interact with a phone call?  
Phone calls on a telephone are inherently (and I would say, clearly)  
the sole domain and responsibility of the telephone operating system.


Telephones that have operating systems... Does anyone remember those  
old rotary assemblages that were mostly mechanical and took up almost  
the same space as a brick of ice cream and had big four-prong plugs?  
THOSE sure as hell didn't have an OS.


I feel old now :).

In any case, it might be more correct to say that phone calls on a  
telephone are ultimately (and conceptually purely) the domain of the  
user. I for one would shudder to think that arbitrary applications on  
my iPhone could interact with the baseband firmware at all, nevermind  
at the level of actually making telephone calls. I hope Apple *never*  
makes this functionality available, ever.


-- Gwynne, Daughter of the Code
This whole world is an asylum for the incurable.
___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Re: iPhone Telephone APIs

2009-05-08 Thread Gwynne Raskind
Apologies for the random e-mail from nowhere; I replied to the wrong  
list.


On May 8, 2009, at 1:17 PM, Gwynne Raskind wrote:


On May 8, 2009, at 1:03 PM, Luke the Hiesterman wrote:

On May 8, 2009, at 10:00 AM, we...@mindspring.com wrote:
If you feel strongly (like I do) that this functionality should be  
made available, file a bug.  I'm thinking there is a legal reason  
this feature is not enabled, but I am unable to confirm my  
suspicions.
Why do you feel you should be able to interact with a phone call?  
Phone calls on a telephone are inherently (and I would say,  
clearly) the sole domain and responsibility of the telephone  
operating system.


Telephones that have operating systems... Does anyone remember those  
old rotary assemblages that were mostly mechanical and took up  
almost the same space as a brick of ice cream and had big four-prong  
plugs? THOSE sure as hell didn't have an OS.


I feel old now :).

In any case, it might be more correct to say that phone calls on a  
telephone are ultimately (and conceptually purely) the domain of the  
user. I for one would shudder to think that arbitrary applications  
on my iPhone could interact with the baseband firmware at all,  
nevermind at the level of actually making telephone calls. I hope  
Apple *never* makes this functionality available, ever.


-- Gwynne, Daughter of the Code
This whole world is an asylum for the incurable.
___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/gwynne%40darkrainfall.org

This email sent to gwy...@darkrainfall.org


___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Re: Problem Embedding Cocoa Framework

2009-05-07 Thread Gwynne Raskind

On May 6, 2009, at 9:43 PM, Marcel Weiher wrote:
Nick, thanks for the tip, you set me on the right track. Here is my  
new understanding of the problem. In my framework target settings,  
the Dynamic Library Install Name is set to:


$(DYLIB_INSTALL_NAME_BASE:standardizepath)/$(EXECUTABLE_PATH)

This is for both Debug and Release. However these expand to  
different things for debug and release:


Debug: @executable_path/../Frameworks/libxml.framework/Versions/ 
2.7.3/libxml

Release: /Frameworks/libxml.framework/Versions/2.7.3/libxml
Is there a particular reason you are embedding a version of libxml  
rather than the one that ships with the system ( /usr/lib/ 
libxml2.dylib )?  Does the somewhat newer version have features that  
you need or have needed bugfixes?


The system installed version of libxml2 on 10.5.6 is 2.6.16. The  
current release of libxml2 is 2.7.3. A quick glance at http://xmlsoft.org/news.html 
 tells us that 2.6.16 comes from November of 2004 and that there  
have been dozens of bug, feature, and security fixes in the *nearly  
five years* since. The only question is why someone who needed libxml  
*wouldn't* embed something more recent than the system provides.


This is another example of Apple's code lagging *severely* behind the  
times.


-- Gwynne, Daughter of the Code
This whole world is an asylum for the incurable.
___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Multiple UIViewControllers don't autorotate correctly

2009-05-07 Thread Gwynne Raskind
Disclaimer: As far as my understanding goes, the iPhone SDK NDA has  
been lifted and I'm free to ask this question here. If for some crazy  
reason this isn't true, please just delete this e-mail.


My iPhone application has one UIViewController for each piece of its  
interface. Each such controller is connected to a view which takes up  
the entire screen. My application runs exclusively in Landscape mode;  
all my view controllers implement:


- (BOOL)shouldAutorotateToInterfaceOrientation: 
(UIInterfaceOrientation)interfaceOrientation

{
return UIInterfaceOrientationIsLandscape(interfaceOrientation);
}

Further, I run with the status bar hidden, and in - 
applicationDidFinishLaunching: my app delegate calls:

[application setStatusBarHidden:YES animated:NO];

I have a method in my main coordinating controller which looks like  
this:


- (void)switchToController:(UIViewController *)newController
{
UIWindow   *window = [UIApplication  
sharedApplication].keyWindow;
// Could also get the window from [UIApplication  
sharedApplication].delegate.window


[self.currentController.view removeFromSuperview];
self.currentController = newController;
[window addSubview:newController.view];
}

This method is called at various times in response to various user  
actions. The currentController property has the retain storage type  
and newController is correctly released (usually autoreleased) by the  
caller; I'm quite certain there's no memory management issue involved  
in this.


When this is called at application startup by the UIApplication  
delegate (from -applicationDidFinishLaunching:, immediately after  
making the window key), everything works beautifully. The first view  
controller picks up the Landscape orientation and displays correctly.


Unfortunately, any subsequent view controller I pass to this method  
displays incorrectly. Specifically, the view is rotated as if for  
Portrait orientation, and is vertically offset halfway off the top of  
the screen. Any modal controllers opened by the controller are also  
wrong.


The problem corrects itself when the device is turned around enough to  
trigger an autorotation.


The two controllers in question - both the working one and the first  
broken one - are set up with practically identical nibs: same  
simulated interface metrics, same attributes in pretty much every way  
in fact. They both override the same UIViewController methods and both  
call super's implementations in the same places. I can't find any  
difference between them to account for this error.


So far I've been able to solve the problem using the SPI [UIWindow  
forceUpdateInterfaceOrientation], but obviously this is not a real  
solution! Not to mention it causes a user-visible rotation of the  
interface from being wrong to being right, so even if it were public  
it'd still be ugly.


Can anyone suggest where I might be doing something wrong, or how to  
correct the problem?


(As a side note that may be related, I used to have the  
UIInterfaceOrientation key in my application's plist, but that caused  
the status bar to pop up in portrait mode and get stuck that way!  
Taking the key out solved that issue.)


-- Gwynne, Daughter of the Code
This whole world is an asylum for the incurable.
___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Re: Does Cocoa layer translate Objective-C objects to C++?

2009-05-04 Thread Gwynne Raskind

On May 3, 2009, at 8:17 PM, johnmadst...@yahoo.it wrote:

I am confused.

I was discussing with a developer about my desire to translate our C+ 
+ code (really simple and few methods and classes) to Objective-C,  
for a Cocoa/Cocoa Touch software.


His answer has been: « I do not understand the reason, considering  
that, after our translation to Objective-C, the Cocoa layer will  
perform another translation to C++. »


Is it true? Cocoa (and/or Cocoa Touch) layer translates Objective-C  
objects to C++?


What is the gain with Cocoa and Obejctive-C, if this is the truth?


I don't know where you got the idea that Cocoa will translate to C++;  
this is complete gibberish. The Objective-C runtime and its objects  
are all implemented in pure C with some support from the compiler; C++  
is only involved if you write a flavor called Objective-C++, and even  
then ObjC and C++ objects are two completely separate entities. If you  
don't write in C++, you won't get C++.


-- Gwynne

___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Re: C string constant-NSString constant without defining twice?

2009-04-28 Thread Gwynne Raskind

On Apr 28, 2009, at 5:15 PM, Kyle Sluder wrote:
Except in the case where one line of code creates the temp file and  
then another immediately uses it and deletes is - as in my case.  
There is zero chance the user could FUS faster than my 2 lines of  
code create and delete the file.

By virtue of you saying that, it will happen.  Murphy's Law loves race
conditions because it always wins.


Not to mention that an attacker putting your app under pressure will  
use nasty tricks to purposely trigger the race condition. Apple has a  
surprisingly comprehensive guide to filesystem (and other) security  
issues, whose advice they blatantly ignore, but you should follow:


http://developer.apple.com/documentation/Security/Conceptual/SecureCodingGuide/Introduction.html

One of my personal gripes: If you look at the implementation of, say,  
mkstemp() and tmpfile() down at the Libc level, you find that  
tmpfile() is implemented *in terms of* mkstemp(). Unfortunately for  
some, tmpfile() also wraps the FD from mkstemp() in a FILE, when I  
want a NSFileHandle. [NSFileHandle  
initWithFileDescriptor:fileno(tmpfile()) closeOnDealloc:NO]. Oops, now  
I have to keep track of the FILE* for as long as the NSFileHandle*  
exists. Ugh! My eventual solution was to roll my own method as a  
category on NSFileManager:


- (NSFileHandle *)openSecureTemporaryFileAndReturnError:(NSError  
**)outError;


This method does all the exclusive atomic opening and unlinking and  
returns a nice NSFileHandle or NSError instead of mucking around with  
errno.


-- Gwynne, Daughter of the Code
This whole world is an asylum for the incurable.

___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Re: Time since Login?

2009-04-22 Thread Gwynne Raskind

On Apr 22, 2009, at 12:00 AM, Jeremy W. Sherman wrote:
How about just nice(1)-ing the process doing the intense processing  
to be

lower-priority, and letting the scheduler sort it all out?


It's my understanding that nice() prioritization is effectively  
meaningless on Darwin, at least according to several open-source  
projects who specifically don't bother with nice()-ing when __APPLE__  
is defined. Was the scheduler changed to make this untrue in 10.5?


-- Gwynne, Daughter of the Code
This whole world is an asylum for the incurable.
___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Re: Problem in displaying image in NSTableView

2009-04-20 Thread Gwynne Raskind

On Apr 20, 2009, at 8:01 PM, Steve Christensen wrote:

personName = @New name;
personAddr = @New addrress;
personPhoto = [[NSImage alloc] initWithContentsOfFile:
@/Volumes/Working/cocoa/Play-NSTableView/Linea.jpg];
if (personPhoto == nil)
{
You need a call to [self dealloc] here, otherwise you leak an  
instance of the class if you can't load the image.


Small correction here: For a failure in -init, call [self release],  
not dealloc. You should never call dealloc directly except from  
dealloc itself to call [super dealloc].


-- Gwynne, Daughter of the Code
This whole world is an asylum for the incurable.
___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Re: Does waitUntilExit really mean that?

2009-04-14 Thread Gwynne Raskind

On Apr 14, 2009, at 4:03 AM, Uli Kusterer wrote:
FWIW, I was having some strange issues with NSTask and setuid child  
processes (...) My eventual solution was to roll my own version of  
NSTask which gave me full control over the way the child process  
was set up, (...) I was able to track down the issue I was having  
with the setuid process once I had the ability to trace the code  
running between fork() and execve().
Care to elaborate on what NSTask is doing differently from your  
solution and what difference this makes (in general and in your  
particular use case)? Did you just hit an edge case, or is there  
some fundamental problem that's likely to bite others? Did you file  
a bug with Apple about this?


It turned out that the problem that was biting me was an extreme edge  
case which really had less to do with NSTask's implementaion than the  
fact that I couldn't step through its source code. The problem  
actually turned out to be in the way the subprocess I was launching  
was initializing itself, but until I was able to trace the codepath of  
the child process - after fork(), before exec() - I wasn't able to  
determine that.


The subprocess in question is one of those cross-platform programs  
that tries to sandbox itself in a way that works on any UNIX or  
Windows OS, and generally ends up making a tremendous mess of other  
processes that try to make use of it.


The major implementation differences between my version and the  
standard NSTask seem to be in two categories: How I know the child  
process successfully exec()d (NSTask uses kqueue() with EVFILT_PROC/ 
NOTE_EXEC, I use a data pipe), and how I manage the descriptor table  
(NSTask uses CFFileDescriptor, I use POSIX-level system calls with  
NSPipe/NSFileHandle). Also, I use a separate thread calling waitpid()  
to raise the task termination notification.


One reason I stuck with my version of NSTask once I'd determined that  
the culprit was actually the subprocess was that I was then able to  
subclass it to create an NSPrivilegedTask using Security.framework and  
all of the same NSTask API I'd already reimplemented. Since the real  
NSTask's details are all squirreled away behind closed-source and  
class clustering (NSTask = NSConcreteTask), it wasn't possible to  
simply sublcass Apple's thing. And  
AuthorizationExecuteWithPrivileges() can be kind of painful for those  
who need finer control over the privileged code being executed (no  
stderr pipe, no PID returned to parent, no control of child process  
environment). Also, while perusing the open-source bits of  
Security.framework, which thankfully include both AEWP() and the  
trampoline it uses, I found some questionable security practices which  
I was able to avoid in my own version. Yes, I did file Radars about  
these issues.


I know AEWP() is extremely don't-use-this-without- 
REALLYGOODREASON, and that any replacement must fall under the  
same criteria. My version does, yes, allow you to shoot yourself in  
the foot with security holes. It also allows you to close some that  
AEWP() doesn't.


I'm planning to publish all my utility code, including my versions of  
NSTask and the NSPrivilegedTask, under an open-source license, so  
eventually I figure people will knock me over the head if I'm barking  
up the wrong tree entirely :).


-- Gwynne, Daughter of the Code
This whole world is an asylum for the incurable.
___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Re: Best way to get a non-repeating random number?

2009-04-13 Thread Gwynne Raskind

On Apr 13, 2009, at 8:36 PM, Michael Ash wrote:

You can put every (unsigned) value you want in there, though in
general it's used passing (unsigned)time(NULL) as parameter.  This  
way

you'll always get a different int.
 No you won't. It's a *random* number generator. The seed simply  
means you
get a different sequence of random numbers. However, random really  
means
RANDOM. I.e. it's perfectly possible to get the same number three  
times in a

row during a sequence. That would still be random.

Technically, I'm pretty sure you will always get a different int.
rand() is a crappy, crappy random number generator, and I would guess
that its algorithm can never return the same number twice in a row.

(If anyone is wondering what the alternatives are, use random()  
instead.)


arc4random() is also pretty decent, if you need cryptographically  
strong random numbers.


-- Gwynne, Daughter of the Code
This whole world is an asylum for the incurable.
___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Re: Does waitUntilExit really mean that?

2009-04-11 Thread Gwynne Raskind

On Apr 11, 2009, at 2:29 PM, Michael Domino wrote:
I ended up throwing out NSTask in favor of popen for running  
hdiutil, and my code seems much more stable now. Did I shoot myself  
in the foot some other way? I'm executing this in a pthread of its  
own. I also kept getting exceptions thrown for nil arguments to  
NSConreteTask, besides the problems getting the standard output  
either partially or not at all. This seems better:



FWIW, I was having some strange issues with NSTask and setuid child  
processes (not setuid root, mind you). I tried to peek at what NSTask  
was doing behind the scenes, and I found some rather confusing usages  
of CFFileDescriptor, kqueue(), and the like in the disassembly. My  
eventual solution was to roll my own version of NSTask which gave me  
full control over the way the child process was set up, from pre- 
fork() to to post-exec(). In particular, I use some of the lower-level  
UNIX calls directly (dup2()/close() instead of CFFileDescriptor,  
waitpid() on a separate thread instead of kqueue(), etc.). I was able  
to track down the issue I was having with the setuid process once I  
had the ability to trace the code running between fork() and execve().


The moral of the story is: Just because Apple provides a closed-source  
high-level Cocoa solution to a low-level UNIX problem, doesn't mean  
the Cocoa way is always the best.


-- Gwynne, Daughter of the Code
This whole world is an asylum for the incurable.
___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


MVC pattern, bindings, and controllers

2009-04-06 Thread Gwynne Raskind
I'm developing a Cocoa application with bindings, as should be  
obvious. I do apologize if this is a newbie question, but my searches  
of the documentation haven't made any of this clearer to me.


I'm trying to make use of the MVC pattern, properly isolating UI code  
from my model objects using controllers, and of course using the  
standard Cocoa view objects. My application communicates with a  
subprocess using NSTask and some NSFileHandles, and stores the  
resulting communication text in an NSMutableString. (I take proper  
precautions to make sure the string doesn't just grow arbitrarily  
large.) To a large extent, the form that the storage of the text takes  
is completely irrelevant.


The reason for this is that I want to display this text in an  
NSTextView. Probably the most efficient way to do that would be to  
provide the NSTextStorage object myself and update it as necessary,  
but I don't quite understand the text system well enough to do this,  
so I'm working with the simpler ways of controlling the content.


This brings me to the Attributed String and Data bindings of  
NSTextView itself. What it wants is either an  
NS(Mutable?)AttributedString or an NSData containing RTF data. I have  
neither of those in my model object; I have an NSMutableString  
containing plain text data.


My understanding of the MVC pattern says that it would be an  
unnaceptable leakage of UI code into the model if I provided methods  
in the model object to return the data in those formats.


This brings me to the controller object, which is where such glue  
code belongs. At the moment, I bind the views to the model using  
NSObjectController. But NSObjectController doesn't provide the  
functionality I need.


The question becomes, do I subclass NSObjectController, or do I  
replace it entirely with my own controller object? For my application,  
which is (for the moment, at least) managing a model object which is  
always the same and handles data that doesn't fit a simple get/set  
paradigm (all my accessor and action methods do some level of state  
management!), it seems like NSObjectController's intention is useless.


Is there some convincing reason I should be sublcassing the Cocoa  
controller instead of writing my own? I don't need management of the  
content object (it's always the same object), editing management (the  
model's data is only displayed by the UI, not managed), or any other  
service NSObjectController provides.


In the same vein, should I even bother worrying about using the  
exposed bindings when managing the NSTextStorage directly is a much  
more efficient solution? And where does the NSTextStorage belong, in  
the model or the controller? The model really seems like it should  
only be responsible for dealing with the NSData of the text it's  
getting from the subprocess.


I realize that all of this suggests that my understanding of the MVC  
setup in Cocoa is less than ideal; I'm eager to be educated :).


-- Gwynne, Daughter of the Code
This whole world is an asylum for the incurable.
___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com