Re: debugging strategy

2009-09-16 Thread Wade Tregaskis
Here is the situation.  We have a large application that has been in  
the field for several years now.  We are adding new feature for our  
next release, and we are testing the new builds against Snow Leopard  
as well as earlier versions of OS X.   Under Snow Leopard, some  
existing functionality has stopped working in a mysterious way.  It  
is crashing deep inside webkit, but the initial symptom is that the - 
drain method is invoked on a object other than an autoreleasepool.   
The class of the object on which -drain is being invoked varies with  
the run.   Obviously, we are not calling -drain deliberately, and I  
doubt that webkit is either, so something is getting screwed up.


So, it seems like memory somewhere is getting corrupted, but where?   
We are also unable to breakpoint in some of the webkit delegate  
methods, so I suspect the corruption is in the stack.  But I do not  
know any good ways of finding stack corruption.


Does the theory of stack corruption seem plausible?  Other ideas?   
And how can one go about searching for a problem like this?


Most likely it's a dangling pointer, most likely because of an over or  
early release.


First stop should be the 'Zombies' template in Instruments, in Snow  
Leopard.  Run your app via it, cause the error, and it should jump  
straight to the object that's missing.


If it doesn't, and you still get -drain sent to a random object, then  
you might consider memory smashing.  But I wouldn't try to go down  
that route unless you have to, as memory smashers are hard enough to  
prove let alone debug.


Wade
___

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: What is the life of the c string returned by NSString's UTF8String method?

2009-09-18 Thread Wade Tregaskis
Or to avoid a copy and raw memory management, you can also query  
directly an NSData from the string using -[NSString  
dataUsingEncoding:NSUTF8StringEncoding] and then use -[NSData bytes]  
as the returned value for this method is guarantee to have the same  
life as the NSData object.


Though of course you must then beware the GC.

Wade
___

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: Zeroing out instance variables

2010-04-16 Thread Wade Tregaskis
>> 3. bzero(individual + individualIvarsOffset, individualIvarsSize);
> 
>  This should cast "individual" to void* before doing the pointer arithmetic, 
> of course.

And of course by "void*" you meant "uint8_t*".  Pointer arithmetic is undefined 
on voids... it happens to be supported by gcc & clang but it's just as easy to 
write correct code.

Wade
___

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: Why Don't Cocoa's (Un)Archiving Methods return Errors?

2011-08-01 Thread Wade Tregaskis
>>> 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.


[[ Sorry for the delay; I've had a busy weekend. ]]

Basically, because there's little validation built-in to NSUnarchiver.  I'm 
going to talk about "attackers" here, but keep in mind that you can substitute 
"random corruption" and the points stand.  So even without an "evil hacker" 
going after your app, you could still hit these issues.

So, some problems:

1) People typically do little validation of values they unarchive, so an 
attacker could substitute all sorts of things which might put the object into 
an unexpected state.  While any individual developer could write their decoding 
carefully, I don't know if all of the standard Apple classes that they're 
likely using have similarly robust validation.  Plus in practice it's sometimes 
tricky to do this validation, and it feels awkward because it can create a lot 
of redundant code within your object.

2) Because the archive can specify any class that supports NSCoding.  While 
technically you can work around this, by subclassing NSKeyedUnarchiver and 
overriding something like -classForClassName:, and having it throw an exception 
for invalid class names, most people don't do this.  And even that is 
preferable to the approach of checking the decoded object's class because it 
prevents any code of that object being run (i.e. the decodeWithCoder:), since 
that code might itself have side-effects.

Some people recommend using property lists instead, since those are more 
restricted while being relatively similar.  They don't necessarily solve issue 
#1, but they are (as far as I know) immune to #2.  You could alternatively 
consider signing the encoded data, if that's possible for your use case.
___

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: Why Don't Cocoa's (Un)Archiving Methods return Errors?

2011-08-01 Thread Wade Tregaskis
>> Any code that throws exceptions will probably leak a few objects, since 
>> according to the ARC design doc the ABI requires not draining autorelease 
>> pools while unwinding the stack.
> 
> Are you sure (or does ARC work differently)?
> 
> :

That'll need to be updated.  If you look at the @autoreleasepool section of the 
ARC documentation, it specifically states that crossing out of one via an 
exception will not drain the pool.  There doesn't appear to be any way, even 
through compiler flags, to change this.

Also, if you look further, at the Exceptions section, it states that by default 
ARC is not exception-safe even aside from autorelease pools.  You can enable 
it, though - and it is enabled by default for Objective-C++ - using 
-fobjc-arc-exceptions.

You'll note that the "Rationale" comments on those two sections specifically 
lay out the expected usage of exceptions:  for programmer error.  That they're 
tolerated [somewhat] in Objective-C++ is simply a nod to history for the sake 
of compatibility.
___

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: Why Don't Cocoa's (Un)Archiving Methods return Errors?

2011-08-02 Thread Wade Tregaskis
>> That'll need to be updated.  If you look at the @autoreleasepool section of 
>> the ARC documentation, it specifically states that crossing out of one via 
>> an exception will not drain the pool.  There doesn't appear to be any way, 
>> even through compiler flags, to change this.
> 
> If an autorelease pool pop is skipped by an exception, then the autorelease 
> pool will not be drained immediately. However, it will generally be drained 
> later, after the exception is caught and handled and some parent pool itself 
> is drained normally.

"Generally"?  In any case, could you see that the ARC documentation is updated 
- it says nothing about this; in fact it clearly states the behaviour I noted.

Also, now that I look at it again closely, the older documentation on 
autorelease pools and exceptions doesn't make sense.

> If an exception occurs, and the thread suddenly transfers out of the current 
> context, the pool associated with that context is drained. However, if that 
> pool is not the top pool on the thread’s stack, all the pools above the 
> drained pool are also drained (releasing all their objects in the process)

Isn't the autorelease pool "of the current context" by definition the topmost 
one?  If the exception takes you out of several autorelease-pool contexts then 
of course based on the first sentence you would expect all of them to be 
drained.  Which I gather is the behaviour.  So the second sentence (in fact, 
most of the rest of that paragraph in the docs) is very confusing.

Also, I don't understand the last bit of:

> Neither is it necessary or even desirable for an exception handler to send 
> release to its autorelease pool, unless the handler is re-raising the 
> exception.

How does re-raising the exception change the autorelease pool behaviour?  If I 
don't release the pool explicitly when re-raising an exception, does that mean 
the pool is 'leaked'?___

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: Why Don't Cocoa's (Un)Archiving Methods return Errors?

2011-08-05 Thread Wade Tregaskis
> I'm not sure really what the argument here is.  What both of you seem to be 
> asserting is "you could construct any object from a file… that file might be 
> maliciously structured to construct objects that behave in evil ways".  This 
> is true, but I'm not sure I see how this differs for *any* API that reads 
> from the file system and constructs objects (as any file loading has to do).  
> Can you give me an example of something that NSCoding (particularly when 
> using keyed archiving) doesn't deal with cleanly, that leads to a security 
> problem not found in other file loading schemes?

I've lost track of threads.  Somewhere recently I responded on this point, or 
one very like it.  In summary, the difference between other APIs as NSCoding is 
that most other APIs don't let the data in the file instantiate an instance of 
any class.  A similar system, property lists, doesn't have this issue.

Someone indicated they like to treat NSArchived documents as code, with all the 
security implications therein.  That's one, fairly practical way to look at 
it.___

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 anyone else dislike Xcode 4?

2011-08-05 Thread Wade Tregaskis
> Well, one thing I just discovered in Xcode 4 and is already annoying me 
> highly is that the app somehow uses CoreAnimation so that now, even though 
> I'm running on battery, it forces the OS to use the Radeon video chipset 
> instead of the integrated Intel's one, which is less power hungry. That is 
> really not good as I go from having 7+ hours (theoretically) to 4+ hours. I'm 
> going to fill a bug as I don't see any reason why Xcode needs to use fancy 
> animations. That really defeats the purpose of having 2 video chipsets.

Xcode's not the only developer tool that does (or at least, did do) this.  The 
easiest workaround - which actually comes in handy at other times, too, so it's 
not bad at all - is to use gfxCardStatus, a free menu item that let's you 
manually control which GPU is used.
___

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: CFMutableDictionary Capacity

2011-08-09 Thread Wade Tregaskis
>>> According the doc, the parameter "capacity" in function 
>>> CFDictionaryCreateMutable() sets the *maximum number* of key-value pairs 
>>> which can be inserted into the container. That is, it's not an *initial* 
>>> capacity.
>> 
>> I think that was a mistake in the docs. The comment in CFDictionary.h in the 
>> 10.7 SDK says:

It is now.  In 10.3 (the first release in which CF was open source) this 
parameter was actually obeyed, and you'd crash [by failed assert] if you tried 
to exceed that capacity.  Sometime since then that changed - in 10.7 the 
capacity parameter is almost completely ignored; it's merely asserted to be 
non-negative.

>> Since CFDictionary and NSDictionary have the same implementation under the 
>> hood, I think the capacity will have the same effect at runtime whichever 
>> API you use.

Not necessarily.  CF and NS objects can actually be different even though they 
are toll-free bridged and ostensibly appear identical.  Whether you create them 
via the CF or NS APIs is generally what makes that difference.  I wouldn't 
worry about it in general, though.

And that said, I don't know if nor to what extent it applies in the case of 
CF/NSDictionary.

> Nonetheless, when defining a mutable dictionary with CF functions, the 
> subsequent insertions take far more time than when using Foundation, e.g.:
> 
>CFMutableDictionaryRef o = 
> #if USE_CF 
>CFDictionaryCreateMutable(NULL, count,
>  &kCFTypeDictionaryKeyCallBacks, 
>  &kCFTypeDictionaryValueCallBacks);
> #else
>CFMutableDictionaryRef([[NSMutableDictionary alloc] 
> initWithCapacity:count]);
> #endif

You could also try calling _CFDictionarySetCapacity on your new dictionary, in 
your CF path.  That will actually pre-allocate space for the given number of 
entries (without restricting you to that many, at least not in 10.7).  That 
might be the difference between the two.  I suspect it is, but it could also be 
a difference of initial hashing algorithms (there are three available to use, 
but you can't choose which*), different callbacks internally, or other factors.

In any case, you should try it and see what difference it makes.  It's 
exported, but SPI.  If it's not defined anywhere, you can define it manually as 
below.

extern void _CFDictionarySetCapacity(CFMutableDictionaryRef dictionary, CFIndex 
capacity);

You could also try the same thing on the NSMutableDictionary - try setting it 
to both your known count but also a small number (not zero nor one though, as 
those are treated specially, not literally).

* = At least, not via any API I'm aware of, and certainly not after creation.  
You could drop down to using CFBasicHash directly and create it how you like, 
of course.  CFBasicHash is the actual implementation of CFDictionary; they are 
"the same".  However, the CFDictionary level of API does do a few special 
things - most obviously, setting "special bits" at creation time which ensure 
the collection works correctly if it contains non-CF types (well, more 
specifically, if you use NULL for any of the key or value callbacks).  Long 
story short, it's almost certainly not worth it. :)
___

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: blocks and retaining CoreFoundation objects

2011-08-10 Thread Wade Tregaskis
>> The ARC specification defines a "retainable pointer" as including those 
>> pointers that have the __attribute__((NSObject)) decoration, so this should 
>> behave as expected under ARC. 
>> 
> 
> I am curious, though, in that CGImageRef is not toll-free bridged to a 
> Foundation class. I had the impression that the API contract was that only 
> bridged CF classes were guaranteed to implement reference-counting methods.

If a CF type isn't explicitly bridged to a particular class, it defaults to 
NSObject.  So you get all the basic object management if nothing else.
___

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: Opening a file read-only?

2011-08-10 Thread Wade Tregaskis
> Try running fs_usage while your app is running, and you’ll be able to see 
> what files it opens and in which modes.
> (Or there’s probably an Instrument for that now?)

There's half a dozen related to file I/O, which unfortunately makes it very 
awkward to use for even simple tasks like this.  You also need to manually add 
in the VM instrument, since it's not in the "File Activity" template, in order 
to see the actual mmap.  fs_usage is much faster.

On 10.7 -[NSData initWithContentsOfMappedFile:] opens the file read-only.  So 
does -[NSData initWithContentsOfFile:].  Even if you instantiate an 
NSMutableData instead, the file is still opened read-only.  I have not tested 
on iOS, but I'd be surprised if it were any different.

Note also that initWithContentsOfMappedFile: is deprecated in 10.7.  There 
doesn't appear to be a replacement; I presume you're supposed to use 
initWithContentsOfFile:, but that really does read the entire file in at init 
time (into a single malloc allocation, no 
less).___

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: Optimizing a loop

2011-08-10 Thread Wade Tregaskis
> //This takes about 6 seconds each search for song*
>for (id key in songsDictionary) {
>NSString *thisSong = key;
>int suppliedCount = [stringValue length];
>int keyCount = [thisSong length];
>//Fuzzy matching
>if(suppliedCount > keyCount){
>match= [StringDistance stringDistance:thisSong
> :stringValue];
>} else {
>match= [StringDistance stringDistance:stringValue
> :thisSong];
>}
>//Get the very best match there is to be found for song.
>if(match < currentFoundValue){
>currentFoundValue = match;
>test = [songsDictionary objectForKey:thisSong];
>dis = [NSArray arrayWithObject:test];
>collection = [[MPMediaItemCollection alloc]
> initWithItems:dis];
>}
>}

Did you ever Time Profile this?  While there are some minor inefficiencies (Why 
initialise 'dis' and 'collection' on every incremental result?  Why initialise 
suppliedCount every loop iteration?), it's likely that all your time is spent 
in your distance calculation.  While you probably assumed that, I'm having a 
hard time imagining what it could be doing that would justify it being so slow. 
 A Time Profile might show you something surprising.  And/or, you could post 
your distance algorithm for the list to look over.
___

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: Retain/Release and Properties clarification

2011-10-07 Thread Wade Tregaskis
> In addition to what Kyle replied, I'd just like to point out that prefixing 
> your *methods* with an underscore is a very bad idea, since Apple does 
> reserve such names and a conflict will bite you at runtime possibly affecting 
> the binary compatibility of your app.

I would argue that underscores are fine to use, but only for the purpose of 
distinguishing "private" or "internal" methods, not namespaces.  If you are 
subclassing a class you don't control (other than NSObject or similar) you 
should prefix your methods with your own identifier, just like you would your 
class name.  This also extends to protocols and delegate methods.  I've 
encountered some rather interesting bugs due to Apple frameworks adding new 
methods with the same names, irrelevant of whether underscores are involved or 
not.  I assure you, Apple won't blink first in these cases. :)
___

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: ARC + return of autoreleased CFType

2011-10-19 Thread Wade Tregaskis
> Following Cocoa convention you'd want to cast it to what and autorelease it? 
> CGColorRef isn't toll-free bridged with anything. If you have been casting it 
> to id and autoreleasing it you might have gotten away with that before but I 
> don't think it's documented anywhere you can do that with CFTypes in general.

You can.  It may not be in the docs, but all CF types are also NSObjects (or a 
subclass thereof).

> You could change the semantics of the method to return a CFRetain()ed object 
> and make it the responsibility of the caller to release it (and change the 
> name of the method too to make it clear) or you can create a UIColor with 
> your CGColorRef, then CFRelease() it and return the UIColor. 
> 
> Mixing autorelease and CFTypes does't seem like a great idea, but I'm 
> prepared for someone to point out a whole piece of documentation I've never 
> seen, that often seems to happen!

No, mixing them is indeed a bad idea.  CF doesn't have auto release pools, so 
anything dealing with CF types is free to not think about them, and in practice 
often does.  I would go with explicitly returning the CGColorRef retained.
___

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: Why does ARC retain method arguments even with full optimization?

2011-11-05 Thread Wade Tregaskis
> The way I understand it with ARC, though, is that it can peek at the stack to 
> see what will happen to a pointer after it’s returned, and cut out some of 
> the unnecessary message sends, so while it’s actually generating something 
> like this:
> 
> - (Foo *)foo {
>   return objc_retainAutoreleaseReturnValue(fooIvar);
> }
> 
> - (void)bar {
>   Foo *foo = objc_retainAutoreleasedReturnValue([self foo]);
>   [self doSomethingElse];
>   [foo bar];
>   objc_release(foo);
> }
> 
> in practice, it’s effectively doing something equivalent to this:
> 
> - (Foo *)foo {
>   return [fooIvar retain];
> }
> 
> - (void)bar {
>   Foo *foo = [self foo]; // -autorelease and -retain cancel each other 
> out here, so they’re both eliminated at runtime
>   [self doSomethingElse];
>   [foo bar];
>   [foo release];
> }
> 
> The messages actually sent to foo are retain and release, a total of two 
> message sends; plus, the autorelease pool doesn’t get involved. That’s a win 
> if you ask me.

Note that (so far as Mac OS X is concerned - I don't know about iOS) this only 
happens with the 64-bit runtime on Intel, on Lion.  Previous runtimes don't 
even have this optimisation, and there's somewhat surprisingly no 32-bit 
implementation of the critical callerAcceptsFastAutorelease().

I'm also curious how this would fare in the presence of instruction reordering 
by the compiler.  callerAcceptsFastAutorelease() as implemented today relies on 
the very next instruction - i.e. the destination of the tail-call-optimised 
return address, being a jump to objc_retainAutoreleasedReturnValue().  Strictly 
speaking there's no reason why that has to be the case - the compiler could 
choose to interleave other, relatively unrelated instructions in there.

That said, in some sense this is all bandaids on bandaids, and this could all 
be moot in a future runtime.  If the runtime decided that overriding 
retain/release were verboten, it could more or less turn retain/release into a 
couple of inlined instructions each.  At least, so a cursory analysis suggests. 
 That wouldn't by itself get rid of this stack peeking business, but if 
compatibility with non-ARC code [and runtimes before a certain date] were 
dropped, then that could go too.___

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: Why does ARC retain method arguments even with full optimization?

2011-11-05 Thread Wade Tregaskis
>> Note that (so far as Mac OS X is concerned - I don't know about iOS) this 
>> only happens with the 64-bit runtime on Intel, on Lion.  Previous runtimes 
>> don't even have this optimisation, and there's somewhat surprisingly no 
>> 32-bit implementation of the critical callerAcceptsFastAutorelease().
> 
> That’s true, in the sense that ARC itself is not supported on the old runtime 
> at all, let alone optimizations related to it.

"ARC is supported in Xcode 4.2 for Mac OS X v10.6 and v10.7 (64-bit 
applications) and for iOS 4 and iOS 5. Weak references are not supported in Mac 
OS X v10.6 and iOS 4."

http://developer.apple.com/library/ios/#releasenotes/ObjectiveC/RN-TransitioningToARC/_index.html___

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: Allocating too much memory kills my App rather than returning NULL

2011-11-07 Thread Wade Tregaskis
>> If calloc() ever returns NULL while attempting to allocate the new
>> grid, I back out all of the successful allocations by passing each
>> array pointer to free().  Then I display an alert to the user to
>> advise them that there is not enough memory for their desired grid
>> size, and suggest trying a smaller one.
> 
> This is not a safe pattern in a multi-threaded application. You may be 
> checking for failed allocations and responding correctly, but to a close 
> approximation no code anywhere else does so. For example, objc_msgSend 
> sometimes needs to allocate memory, and has no way to recover if it cannot. 
> If some other thread were working at the same time you caused allocation 
> failures, then that thread is likely to crash.

'course, that's just one defeatist's opinion.  As a counter-opinion, I think 
that handling runtime errors is wise, and I've seen many crashes averted in 
practice (in multi-threaded code) in cases just like this.
___

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: Allocating too much memory kills my App rather than returning NULL

2011-11-07 Thread Wade Tregaskis
> Also I'm pretty sure the iOS memory allocator is multithreaded, and
> that Apple's code would be good about checking for runtime failures.
> If it does not, then that is a bug in the iOS.

That's my opinion too, but there are plenty of people within Apple who are 
vehemently against it.  So while I encourage you to file bugs, for your own 
sanity you shouldn't trust Apple's code in this respect, and should code 
defensively.  Obviously there's only so much you can possibly do in that 
respect, though.
___

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: Allocating too much memory kills my App rather than returning NULL

2011-11-08 Thread Wade Tregaskis
>> Before I started writing iOS code I did embedded systems development
>> and Mac OS X device drivers.  In both of those environments, Failure
>> Is Not An Option.  While you can certainly run out of memory or
>> encounter other errors, one just has to back out gracefully.
> 
> This turns out not to be practical in a complex layered application 
> environment. How do you even begin to write recovery code when any method 
> dispatch could fail? How do you test it?

This is a straw man.  The existence of tricky edge cases does not justify 
careless code (nor imply that objc_msgSend is careless).

For background, to anyone still following this thread at this point, I worked 
for several years in Apple's performance tools team(s).  The vast majority of 
"performance" problems seen in bug reports, developer kitchens, WWDC labs, dev 
forums and mailing lists revolve around memory.  A substantial fraction of 
those are specifically allocation failures - whether due to bogus arguments to 
malloc et al, or memory exhaustion on iOS, etc.  The vast majority of those 
come to people's attention through crashes in their apps, often after shipping. 
 Most of those crashes could be averted by simple error checking and graceful 
failure.  Simple as that.
___

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: Allocating too much memory kills my App rather than returning NULL

2011-11-08 Thread Wade Tregaskis
> Simple as that, eh? Being able to gracefully handle all out of memory 
> situations to me seems as "simple" as being required to treat every single 
> method / function call as potentially raising an exception, and requiring the 
> developer to add handlers + cleanup code. No existing code (OS or apps) is 
> exceptions safe at every single line of source code. At the very least this 
> would require a complete rewrite / review of every single line of existing 
> source code in both OS and apps, something that seems neither simple nor 
> practical to me.

Another straw man.  We could, hypothetically, talk about the probabilities, but 
neither of us has sufficient data.  Like most things in software development, 
it's up to each individual to decide where the balance is between defensive 
coding and whatever trade-offs it requires.  My aim here has been to persuade 
anyone listening that this is something they have a meaningful influence over.  
I hope for my own selfish sake that I've succeeded at least a little, just in 
case I end up using code written by any of our listeners.
___

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: Crash and dispatch queue

2011-11-17 Thread Wade Tregaskis
> [myObject saveDataToFile];

What does this method actually do?  From the sounds of it your analysis has 
determined that running this from a thread other than the main one is 
problematic.

If so, first thing is to figure out why the thread matters at all.  If you 
can't make it thread safe, then perform your work asynchronously as in your 
first case, but wrap the call to save in a dispatch back to the main queue.
___

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: checking if directory is writable

2012-01-12 Thread Wade Tregaskis
> I was of the understanding that Apple's recommendation was just to try the 
> operation you wanted to perform, and handle the error if there is one. This 
> is taken from the NSFileManager header, directly above the isWriteableAtPath: 
> declaration:
> 
> "The following methods are of limited utility. Attempting to predicate 
> behavior based on the current state of the filesystem or a particular file on 
> the filesystem is encouraging odd behavior in the face of filesystem race 
> conditions. It's far better to attempt an operation (like loading a file or 
> creating a directory) and handle the error gracefully than it is to try to 
> figure out ahead of time whether the operation will succeed."

There's a tendency to create a false dichotomy there, though.  It's true that 
only checking in advance is erroneous, but advanced checks can be useful if 
done appropriately.  For example, when the user first selects a file you could 
sanity check it, and if it looks like something is wrong you can subtly warn 
the user.  The key is to not stop them actually trying - the only true gauge is 
whether the real operation succeeds or not - and not to be too invasive.  For 
example, think about the standard Open dialog which by default disables files 
of unsupported formats.  Or the variant of the same which doesn't disable them, 
but shows a passive warning message within the dialog window if you select one.

It's not something to be considered too lightly, though, because to do a really 
good job of it takes more work than you might think.  For example, if you're 
going to indicate that the user can't seemingly write to the target folder, you 
really should be watching that folder for changes.  When it does become 
readable, you can remove the warning immediately, providing clear feedback to 
the user that a) they've fixed the issue correctly, and b) your app is paying 
attention.  Think about installers that require you to quit certain open apps, 
and compare the ones that make you re-run the installer manually versus those 
that will get immediately underway as soon as the apps are closed.
___

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 slowing down bindings updates possible?

2012-01-12 Thread Wade Tregaskis
> The result of this is that the UI updates really frequently and the
> estimated time to complete and the download rate jump around a lot. I
> would love it if I could tell cocoa to only update the UI once per
> second instead of immediately when the property key changes.

I don't believe there is such a feature.  Though I wouldn't be surprised if 
someone out there has already implemented a proxy like you suggest.

> With a bit of work I could probably set up a proxy object for each
> download that would do something like that and use timer, but it would
> be a lot of messy code. I could also just delay updating the
> _bytesDownloaded on a queue. Or a third idea is to cache the estimated
> calc time and rate and then only recalculate the value at most once
> per second.


I think if you're going to follow the MVC paradigm, you should be sure to 
update _bytesDownloaded immediately - that's your model, which should always be 
accurate.  Any smoothing or aggregation or whatever else you want for UI 
purposes should be handled in your controller.

So, either a reusable proxy object (if you'd like to stick with bindings), or 
just coded in your controller such that it won't update the view at more than N 
Hz (in which case simply modifying the UI "manually" from your controller is 
probably the easiest option).

Either way the implementation shouldn't be that tricky - just a timer and a 
last-updated timestamp.
___

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: How to get the dispatch queue for the current thread's runloop?

2012-01-27 Thread Wade Tregaskis
> It looks like I should just call dispatch_async, but I'm unsure which 
> dispatch queue to use. dispatch_get_main_queue only works for the main 
> thread. Can I use dispatch_get_current_queue? I'm unsure of what this does 
> when called on a background thread. The API docs say "If the call is made 
> from any other thread, this function returns the default concurrent queue" … 
> is that a queue associated with the thread's runloop, that's guaranteed to 
> execute tasks on that thread?

Where do they say that?  That's surely wrong.  The man page says that in that 
case it returns the default-priority global [serial] queue.  
http://developer.apple.com/library/mac/ipad/#documentation/Darwin/Reference/ManPages/man3/dispatch_get_main_queue.3.html
___

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: How to get the dispatch queue for the current thread's runloop?

2012-01-28 Thread Wade Tregaskis
> Where do they say that?  That's surely wrong.  The man page says that in that 
> case it returns the default-priority global [serial] queue.

Nevermind, I'm not paying enough attention.  I figured you'd have to return a 
serial queue, so my brain conveniently ignored the fact that the global default 
queues are all concurrent.

FWIW here's the state of affairs on 10.7.2:

Main queue: com.apple.main-thread (0x7fff7c2aa980)

Default concurrent queues:
High priority: com.apple.root.high-priority (0x7fff7c2ab240)
High priority (overcommit): com.apple.root.high-overcommit-priority 
(0x7fff7c2ab300)
Default priority: com.apple.root.default-priority (0x7fff7c2ab0c0)
Default priority (overcommit): 
com.apple.root.default-overcommit-priority (0x7fff7c2ab180)
Low priority: com.apple.root.low-priority (0x7fff7c2aaf40)
Low priority (overcommit): com.apple.root.low-overcommit-priority 
(0x7fff7c2ab000)
Background priority: com.apple.root.background-priority (0x7fff7c2ab3c0)

Current queue as seen by:
Default priority concurrent queue: com.apple.root.default-priority 
(0x7fff7c2ab0c0)
Main thread (outside of dispatch queue): com.apple.main-thread 
(0x7fff7c2aa980)
Random pthread: com.apple.root.default-overcommit-priority 
(0x7fff7c2ab180)
Main queue: com.apple.main-thread (0x7fff7c2aa980)

Note that it returns an over-commit queue if there is no other answer.  
Over-commit queues differ from the normal queues in that they have no limit to 
the number of threads that may be servicing them concurrently (other than the 
general limits on thread numbers).  I expect there's a very deliberate reason 
why this is done, but it does open the possibility for poorly written code to 
over-subscribe the system and bring down the overall performance.
___

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: [Obj-C] if (self) vs. if (self != nil)

2012-02-24 Thread Wade Tregaskis
> self = [super init];
> if (self)
> {
> }
> return self;
> 
> self = [super init];
> if (self != nil)
> {
> }
> return self;
> 
> The Xcode samples promote the first variant, but I'm wondering if the
> second one is more correct?

No.  The more common convention in (Apple's) ObjC is to use implicit boolean 
values, though an explicit test against nil is fine if that's your preference.

> The "nil" is defined as follows (jumped to definition)
> 
> #define nil NULL
> #define NULL ((void*)0)

I'd hazard to say that's an implementation detail.  While you can compare 
object pointers against NULL, it's strongly against convention - you use nil 
for pointers to ObjC objects, NULL for other types of pointers.  Hypothetically 
this protects you from any future changes in how objects are distinguished from 
"regular" pointers.

> I also heard that generally speaking NULL is not necessarily always
> equal to 0 on all architectures.


That definition is quite archaic.  Though technically speaking it's true, and 
is thus an argument for actually using NULL rather than 0, it's not the only 
such argument by far*, and in any case there's enough momentum behind NULL == 0 
that this will almost certainly never change.

* = For example, more important arguments are for readability in code, and 
because 0 is an integer whereas pointers are not.  And that a test against zero 
is faster than a test against any other specific integer on all modern hardware.
___

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: [Obj-C] if (self) vs. if (self != nil)

2012-02-24 Thread Wade Tregaskis
> if(self == nil)...
> if(self = nil)...
> if(nil == self)...
> if(nil = self)...
> 
> The 1st & 3rd are the correct conditions, the 2nd & 4th are typos. But the 
> 2nd compiles and gives incorrect behavior, while the 4th fails to compile.
> 
> Of course if(self) is not subject to that kind of typo, but if you're going 
> to insist on the verbose version, you might as well use if(nil == self).

Scott makes an excellent point.  I just want to emphasise it by saying how 
useful that has been to me over the years - countless bugs killed at birth.

I will admit it took me a while to get used to it, but the sooner you stop 
thinking about it the sooner it's natural.  You may run into people who dislike 
it on religious grounds, however.  For example, Google's internal style rules 
forbid it.  Try to make sure you're paid by bug count, if you find yourself in 
that situation. ;)
___

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: [Obj-C] if (self) vs. if (self != nil)

2012-02-25 Thread Wade Tregaskis
>if(nil != (self = [super init]))
> 
> Myself I find it elegantly brief and imminently readable.

I don't mind it, but to me it begs the question of what it offers over:

self = [super init];
if (self) {

My rationale is, generally you avoid assignments within conditionals because 
it's just plain awkward.  The if (self = [super init]) pattern is a rare 
exception, that is justified purely by convention at this point.  If you're 
going to break that convention, and increase the verbosity to boot, you should 
probably just revert to fundamentals - i.e. treat it like any other assignment 
and test.
___

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: Xcode - An Apple Embarrassment

2012-02-29 Thread Wade Tregaskis
> *No*. I've said it before (right here) and I'll say it again; this is *not* 
> jumping to the documentation, and it is *not* doing what Xcode 3 did. It 
> switches to the documentation window and it enters the double-clicked word 
> into the search field, and it does the search, but it doesn't display the 
> actual documentation on the double-clicked word.

Indeed, the regressions around this simple piece of functionality are 
disturbing.  I also find that it rarely handles double clicks correctly.  I 
have to triple or quadruple-click much of the time.  It's often faster to just 
bring up the organiser (command-shift-2, obviously) and navigate to the desired 
docs directly, than play some kind of bizarro skill game with my mouse button.

> Once again I put forward my pet wild-and-crazy "dog food" theory that the 
> people at Apple do not actually *use* Xcode for serious work. I know it 
> sounds wild and crazy, but I have two kinds of evidence for this theory:

Occam's razor (and my own nearly four years working on developer tools at 
Apple) will present a different explanation:  Xcode is used exhaustively within 
Apple, but the Xcode team just aren't good at producing a solid product.  I'm 
not sure why that is; all the people I know on the Xcode team are very good 
developers, at least individually.

Someone else pretty well hit the nail on the head earlier when they suggested 
that developer tools just aren't given much top-level interest.  I don't know 
if that can be blamed for the end result though.
___

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: Unclear on -initWithBytesNoCopy:

2012-03-05 Thread Wade Tregaskis
Perhaps the only 'correct' solution to this problem is to fall back to the 
CFString level, where you can pass a custom CFAllocator to e.g. 
CFStringCreateWithBytesNoCopy().  That way the lifetime is effectively managed 
by the CFString, so it should behave correctly in all cases.

'course, the implementation is relatively awkard compared to what *should* be a 
single method call.  Perhaps a variant of initWithBytesNoCopy:, one that takes 
a block with which to free the bytes, should be created.
___

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: Unclear on -initWithBytesNoCopy:

2012-03-05 Thread Wade Tregaskis
> I’m not sure I’d want that either, though. If the original string was a 
> 200-page dissertation and you took a one-word substring from it, it doesn’t 
> seem reasonable to keep the whole 200-page dissertation all in RAM just to 
> keep the one-word substring around.


But that's a very old problem that's been dealt with in numerous ways over the 
years.  It could easily be addressed as an implementation detail.

The key point however is that CFString/NSString are nowhere near that smart, 
and they're not likely to be (GNUstep or others aside).  If you're dealing with 
a large chunk of text like a dissertation then you're probably dealing with a 
lot of other elements as well, and using much higher-order objects to represent 
things.
___

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: Filter an array

2011-07-29 Thread Wade Tregaskis
> Further to earlier answers, bear in mind you've got no guarantee that file 
> extensions are correct, or even exist. Plus of course, you might have both 
> .jpg and .jpeg. You might well be better iterating through, finding the UTI 
> of each file, and working from that.

Oooh, that's kind of embarrassing. :)  Yes, that's a very good point, that we 
all should have realised before worrying about the details of file extension 
comparison.  So I'll retract my prior recommendations and instead suggest using 
something like:

// Provided parameters:
//
//paths:  Collection of NSStrings, the absolute paths of the items in 
question.
//supportedTypes:  Collection of UTIs (NSStrings) that you're looking for.

for (NSString *path in paths) {
NSURL *url = [[NSURL alloc] initFileURLWithPath:path];
NSString *uti = nil;
NSError *error = nil;

if ([url getResourceValue:&uti forKey:NSURLTypeIdentifierKey 
error:&error]) {
for (NSString *supportedType in supportedTypes) {
if (UTTypeConformsTo(uti, supportedType)) {
// You have a match.
}
}
} else {
// Handle error
}
}

There's a lot of nasty enumeration there, rather than hashtables which make me 
much happier, but I don't know of a better way off hand.

However, -[NSURL getResourceValue:forKey:error:] is only available in iOS 4.0 
and later.  So you'll have to find another route if you're targeting earlier 
than that.

Also, if your paths are actually the contents of a folder (or folders), you 
could use -[NSFileManager 
enumeratorAtURL:includingPropertiesForKeys:options:errorHandler:], which will 
handle the enumeration for you as well as possibly being faster - one of the 
promised potentials of that method is that, since you tell it up front what 
file properties you're interested in, it can pre-fetch and/or batch-fetch them. 
 Again, though, that's only available on iOS starting at version 4.0.

Addendum:  See also the Uniform Type Identifiers Overview for more information 
on UTIs.  You'll note, for example, that I didn't just do isEqualToString: when 
comparing them, and for good reason - all explained in the docs.
___

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: Analyzer Questions

2010-02-02 Thread Wade Tregaskis
> - (CGPDFDocumentRef)getPDFDocumentRef:(const char *)filename { 
>   CGPDFDocumentRefdocument; 
> 
>snip...
> 
>   document = CGPDFDocumentCreateWithURL(url); 
>   return document; 
> } 

The CF convention is that functions and methods that return a literal reference 
to an object - that is, the caller doesn't receive ownership of it - use the 
verb "get", as you have above.  Functions and methods which do return ownership 
use the "copy" or "create" verbs.

Clang Static Analyzer uses these cues to decide what it thinks you should be 
doing.  If you rename your above method to createPDFDocumentRef:, you should 
find it's a lot less confused.

Wade
___

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: Analyzer Questions

2010-02-02 Thread Wade Tregaskis
>>  Thanks, changing several methods to use the 'new..." naming standard did 
>> the trick. Using create as suggested by Wade didn't fix the problem, which 
>> explains why another method (createBitmapContext) was showing similar 
>> behavior. 
> 
> Create only works with functions (CF convention). new only works with methods 
> (Cocoa convention).

My apologies, I was extrapolating from 'copy', which is supported in both.

Tangentially, I find it odd that 'new' is recognised as it puts me in mind of 
the old 'new' class method, which has been deprecated and frowned upon for as 
long as I can remember.

Wade
___

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: End Of Method Releasing Order?

2009-06-01 Thread Wade Tregaskis

does it matter which order objects are released at the end of a
method?  example:

-=-=-=-=-

- (void)applicationWillTerminate:(NSNotification *)notification
{
FourLines *fourLines = [[FourLines alloc] init];
fourLines.field1 = field1.text;
fourLines.field2 = field2.text;
fourLines.field3 = field3.text;
fourLines.field4 = field4.text;

NSMutableData *data = [[NSMutableData alloc] init];
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc]
initForWritingWithMutableData:data];
[archiver encodeObject:fourLines forKey:kDataKey];
[archiver finishEncoding];
[data writeToFile:[self dataFilePath] atomically:YES];

[archiver release];
[data release];
[fourLines release];
}


In the case above, and in general, no - most retains you'll have on  
other objects are for your own use, and if they keep a reference to  
anything themselves, they are responsible for retaining it on their  
own behalf.  If, however, you have a retain on something on behalf of  
something else - e.g. you hand a struct to some function, which  
contains a pointer to an object that you have to retain on its behalf  
- then the order can matter, though for better or worse such scenarios  
often allow you to get away with it, whether coincidentally or luckily.


Wade
___

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: Profiling a drag and drop operation

2009-06-06 Thread Wade Tregaskis
I don't know how well I understand the output I got from it.  I  
found an area of my code , shark said was taking up about 4.8%,  
which was about the third highest entry in the results.  Despite  
making that change the application, doesn't seem to load the file  
any faster.  Additional Shark profiling show that changed code is  
now longer showing up in the profiling results.


The top entries are all in the operating system or kernel.  The top  
two are shandler 10.3% and copypv 6.1%, which are both kernel  
functions.
The third entry is lseek with 4.1% in libSystemB.dylib.  When I  
expand this entry it shows the code that I recently changed, which  
is trying to check to see if the read position has reached the end  
of the file.  I'm caching the end position of the file and comparing  
the current file position against it.  I suspect the lseek command  
is what determines the current file position.  I'm not sure how I  
could improve the check or why it would be slow.


It may be that you're simply blocked much of the time waiting on e.g.  
the hard disk.  You can use Time Profile (All Thread States) to see  
all your time, whether running or not.  Or you could take a System  
Trace to get an intuitive view (the Timeline) of what's going on with  
regards to blocking.  The Shark manual is a good thing to read through  
(the relevant chapters, at least); it'll explain what you're seeing  
and has a kind of Q&A addendum to each chapter, for common patterns  
you'll see.



Typically the most common problem with understanding Shark output is
that it defaults to Heavy mode, even though Tree is a lot more
understandable and useful.


The two modes are good for different things.  Heavy view is more  
intuitive for newbies, and gives you conclusive answers much faster in  
those cases where it is applicable.  In ATS (All Thread States) mode  
particularly so.



Note that your delayed sample trick is unnecessary and potentially
harmful if the sampling goes on for a significant time after your
freeze has stopped. You can start and stop Shark by simply pressing
option-escape, so you can press that as you start your drag, then
again as soon as it unfreezes to ensure that you're only sampling the
right area.


Though the point is well made, I would like to add that in a situation  
like this I'd expect you'd be able to use the data mining commands to  
quite effectively filter out unrelated code.  Though presumably the  
app is largely idle before the drag starts and once it is fully  
processed, so a standard Time Profile won't have any extraneous data  
anyway.



Spin Control is another useful tool here, as it can automatically
start and stop sampling in response to an application no longer
responding to events. Its output is not as comprehensive as Shark's,
but you probably don't need the extra information at this point.



Shark has an analogous feature - choose 'Unresponsive Applications'  
from the Sampling menu.  It's implicitly recording while active, so  
don't be dissuaded by the Start button being disabled.


Wade
___

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: literal strings - who do they belong to?

2009-07-12 Thread Wade Tregaskis
I know you guys probably know this, but to be technically accurate,  
there is no guarantee the return value of stringByAppendingString  
returns an autoreleased string.


While your point is true, it's not actually a rebuttal - you can  
assume objects returned from such methods are autoreleased, because  
that's the contract given.  Whether they're cached or singletons or  
whatever else, they must obey the policy that they'll stick around  
'til the next flush of the current thread's current autorelease pool.   
You just can't safely handle the memory management otherwise,  
especially in multithreaded cases.


Unfortunately, this contract isn't always followed.  Lots of people  
"optimise" away this policy instead of doing a "superfluous" 'return  
[[foo retain] autorelease]'.  @propertys are by default atomic  
(meaning they follow this policy) for a reason.  In manually written  
code, you have to be careful, but you're pretty safe with object  
creation methods, and especially those in Apple frameworks.  If you  
find any that don't follow this policy, you should file a bug report.


Wade
___

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: literal strings - who do they belong to?

2009-07-13 Thread Wade Tregaskis

{
NSData *data = [[NSData alloc] initWithBytes:foo length:bar];
const char *bytes = [data bytes];
[data release];
CrashByDoingSomethingWithBytes(bytes);
}

Why should this sort of thing be expected to work, just because the
property in question happens to be an object?


A facetious example, because in reality you never know where pointers  
are coming from when returned from some other method.  Why should you  
ever expect any use of any returned pointer from any object to work?


That there are some well known cases doesn't negate the fact that this  
is quite problematic to assume this universally.  Completely  
impractical, in fact.


One could argue that NSData should [[self retain] autorelease] itself  
in that case.  But there are valid performance concerns particularly  
with NSData, which may be why it doesn't.  Certainly it probably  
didn't do it originally because no one anticipated it would be a  
problem, not because of any deliberate design choice.



http://developer.apple.com/iphone/library/documentation/Cocoa/Conceptual/MemoryMgmt/Articles/mmRules.html

"... if you need to store a received object as a property in an  
instance variable, you must retain or copy it."


Thus, apparentl doing

NSString *s = someobject.somevar;

is essentially against the rules.  You should always use

NSString *s = [[someobject.somevar {retain|copy}] autorelease];

(To my eye, not common sense, but understandable)


Note that it says instance variable, not local variable.  It should  
also so global variable, for completeness; anything outside the scope  
of the current function or method.


The general assumption in Cocoa is that the received object is valid  
for the rest of your function, which is in fact a simplification (of  
it being valid 'til the next autorelease pool or next destructive  
change, the latter part being the concession to reality rather than an  
intended contract).


In any case, if you want to take it as aggressively as you've  
suggested, then you can try that, but it's still wrong; by the time  
you get the result it may already have been released.  This is the  
entire point behind autorelease pools; to allow any object to return  
any other object to any other code without the nightmares.  As I said  
in my original reply, you just can't live happily in Cocoa if you  
don't accept this, and follow it.


That many objects don't follow, or correctly follow, this approach is  
a sad excuse not to try to do so now and in future.  There will always  
be exceptional cases, but they can remain exceptional.  And many can  
be fixed.  These sorts of issues can be huge time wasters, I know all  
too well.  Which is why I'm so strongly advocating you to follow the  
policy I suggested.


There's also a high cost, in CPU cycles and memory, to retain/ 
[auto]release in such an excessively defensive way.  And have fun  
using Object Alloc to find real problems once you've added these  
superfluous retain/release/autoreleases to every return value in your  
entire program.


"A received object is normally guaranteed to remain valid within the  
method it was received in (exceptions include multithreaded  
applications and some Distributed Objects situations, although you  
must also take care if you modify the object from which you received  
the object). That method may also safely return the object to its  
invoker"


This is written quite conservatively to address the fact that a lot of  
code is very poorly written in this regard.  But again, bad history  
doesn't justify bad future.  @propertys make it nice and easy to avoid  
these issues by doing it right to begin with; being "atomic".  There  
are certainly valid scenarios where you can justify opting out of  
this, but only a few.  And you should certainly document them very  
carefully.  Or better yet, use an alternate but still safe pattern,  
such as atomic-retain/copy-return).


However, the last sentence about the method being able to return the  
object to its invoker is just bizarre - it glosses over things like  
'this method has an autorelease pool', etc.  I would have thought  
that it makes more sense to simply state that you should [[o retain]  
autorelease] anything you want to return at all levels, rather than  
implicitly insisting that the bottom level will have done it.


That document is written at a very introductory level and assumes if  
you're conscious of autorelease pools, you're aware of their caveats.   
Beyond that, what you've suggested is overly defensive again.   
Sometimes necessary for complex control flow (e.g. if you yourself  
return the raw bytes of an NSData, or if you are indeed escaping from  
the topmost autorelease pool), but the cost of all those autoreleases  
will rapidly add up to something significant in many programs.   
Getting it right at the originator is simpler, and more efficient -  
for all you know any given method returns a constant (or any other  

Re: literal strings - who do they belong to?

2009-07-13 Thread Wade Tregaskis
There's also a high cost, in CPU cycles and memory, to retain/ 
[auto]release in such an excessively defensive way.  And have fun  
using Object Alloc to find real problems once you've added these  
superfluous retain/release/autoreleases to every return value in  
your entire program.


But wouldn't adding those retain/autoreleases to every accessor in  
your entire program have the same effect?


Perhaps to an extent, if the object in question lives a long time  
relative to the number of gets of it.  But in any case, the same  
object may be passed down a very long callstack, so the difference  
could be between a single retain]autorelease] and a thousand of them.


It's still easier to interpret in tools like Object Alloc, though -  
you can clearly see the retain]autorelease] for each getter scattered  
throughout other uses.  The periods you're most interested in are  
likely to be between calls to the getter (on the same thread, at  
least), and so much less noisy.


Wade
___

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: literal strings - who do they belong to?

2009-07-13 Thread Wade Tregaskis

id obj = [dict objectForKey:@"whatever"];
[dict release];
NSLog( @"this will crash %@", id );


And if you extrapolate this example further to the case where [dict  
release] is called on another thread, you're in a real pickle.   
Ideally, objectForKey: would retain]autorelease].


This multithreading argument is completely irrelevant.  If your code  
is not thread safe, that is a completely independent issue which  
atomic and retain/autorelease will not solve!


Fair to say.  I contemplated expanding on this point previously, but  
declined by way of laziness.  You sods proffer no mercy, do you? :P


Atomic properties (nor autorelease pools) are definitely not a panacea  
for multithreading.


That said, bear in mind what my suggestion does buy you:  if  
NSDictionary did atomically retain]autorelease] from objectForKey:,  
then it would be thread-safe to mutate the dictionary.  If this is  
just some big global, say - some kind of cache or hash table or  
whatever else - it may well be a totally appropriate level to  
implement that thread safety.


If, however, as Peter points out, it's just some little dictionary  
buried in some bigger class, then it's likely not the level you want  
to resolve mutual exclusion at.  But it doesn't necessarily hurt;  
maybe your app will still draw things out of order, but at least it  
doesn't crash.


Furthermore, in the example above 'dict' should be owned by the  
execution function at that time, since it's either explicitly owned,  
or was returned to it via retain]autorelease].  See how it recurses?   
If everyone plays by these rules, life gets a whole lot simpler.


Keep in mind the dictionary case is just an example, not to be taken  
too literally for the purposes of this discussion.


The warning I've tempered this advice with throughout is with regards  
to performance.  We all cut corners sometimes in the name of necessary  
practicality.  Otherwise we'd all be programming in Lisp instead of  
this clumsy C stuff.  And you should have seen some of the internal  
discussions over whether @property should be atomic by default or  
not.  But the performance mantra applies as always:  correct first,  
optimal later (though, please, not too much later :) ).


Wade
___

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: The current preferred method for fetching HTTP URLs for IOS

2012-03-09 Thread Wade Tregaskis
> FWIW, my view is that it depends on what your requirements are. For a simple 
> request, you can go with an [NSString stringWithContentsOfURL] wrapped in a 
> call to dispatch_async to avoid blocking the main thread. 

But keep in mind that threads are not free and there are a finite number 
available to each concurrent queue.  You can experience unexpected delays if 
you abuse them.  You may even get into deadlock.

I'm not saying not to use that convenience method, but you should consider if 
your usage of it will be sufficiently light.
___

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: [Q] Why is the threading and UI updating designed to be done only on a main thread?

2012-03-14 Thread Wade Tregaskis
> Threads themselves are very useful; multiple threads taking user input and 
> updating the display to the user are not really useful, and the request for 
> them more often than not betrays a lack of understanding of threading.

So you think it'd be great it every GUI app shared the same serial queue for 
all interactivity and drawing?  Boy do I have a Mac Classic to sell you...

The reality is of course more of a compromise.  It's quite common to do drawing 
across multiple threads, though you still synchronise the final "blits" around 
a single thread (i.e. the main thread).  Likewise even event handling is often 
effectively multi-threaded, because you dispatch from the main thread to a 
variety of tasks, queues or worker threads.

Having a UI framework that either offloads some of this for you can actually be 
very useful.  It would also be closer to the user experience we're trying to 
portray - for example, that each document on an app is totally independent.  
Having all documents hang because one is having issues (Safari I'm looking at 
you, you evil bastard) completely breaks that illusion.
___

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: [Q] Why is the threading and UI updating designed to be done only on a main thread?

2012-03-14 Thread Wade Tregaskis
>>  Likewise even event handling is often effectively multi-threaded, because 
>> you dispatch from the main thread to a variety of tasks, queues or worker 
>> threads.
> 
> But then you are receiving the events on the main thread? What do you
> mean? If you receive events on the main thread, and dispatch the work
> to be done to other threads, I'd say that is quite in line with how
> things are currently done on OS X.

That's kind of my point.  For a given single input device, there's a definitive 
ordering of events.  So at some level you have that.  It also makes a lot of 
sense to serialise all input events, on the assumption that it's a single human 
driving them, since most humans expect their keystrokes and mouse actions to be 
interleaved in the same order they performed them in.

At some higher level, those events invariably cause actions to be taken, which 
may be "trivial" (show/hide a view) or complex (load a saved document, perform 
a render, whatever).  It's common practice to farm those off manually, today, 
in Cocoa.  Based on perceived complexity and wallclock time of the task, 
generally.  Not necessarily tied to a particular logical resource (e.g. a 
document).

On the other hand, you could have an event handling framework which dispatched 
events to any of multiple threads/queues/whatever for you.  For example, each 
window might have its own queue.  This actually makes a lot more sense in many 
cases, as a default, since many actions within a single window/document are 
successive, not concurrent.  If they are concurrent, you could then go to the 
trouble of manually dispatching things to other queues, or otherwise realising 
that concurrency.

[[ And if you have multiple windows per document, you could always configure 
them to share the same queue, if that's appropriate. ]]

As others have pointed out, various major systems have done this in the past, 
to varying degrees.  BeOS, for one.  I also believe MFC (Windows, pre-.NET, 
basically) does something like this.  It might seem alien to traditional Mac 
developers, but it's far from exceptional.

Though I say all these merely to emphasise that it's possible.  To actually 
consider revising all of Cocoa around such a new paradigm would be an 
extraordinary undertaking.
___

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: [Q] Why is the threading and UI updating designed to be done only on a main thread?

2012-03-14 Thread Wade Tregaskis
> The problem of course, is that in order to allow that, the framework itself 
> has to be locking things all over the place, regardless of whether or not an 
> app is actually accessing any particular data from multiple threads, because 
> now the framework has to assume that might happen.

Yes and no.  Or, maybe.  There are many possible implementations.  For example, 
you could have a designated thread/queue for each separate 
window/document/whatever, as I suggested, in which case the mutual exclusion is 
largely implicit and disappears in the noise.

In any case, uncontested locks (if done correctly) are not very expensive at 
all.  Not at the granularity we're talking about here.
___

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: [Q] Why is the threading and UI updating designed to be done only on a main thread?

2012-03-14 Thread Wade Tregaskis
> I don't like the idea of a multithreaded aproach by default, because as a 
> general rule, you
> should not make your application multithreaded unless you have a good
> reason.

a) The reality is that Cocoa already exposes you to a lot of concurrency and 
asynchronisity, and is only going to do much more so in future.  That said, 
there are limits to what can be done here (especially with dispatch queues; the 
way GCD paradigms interact with callback patterns is far from seamless).

b) This convenientional wisdom is, in my humble opinion, antiquated.  It's just 
the reality today that multi-threaded performance scales better than 
single-threaded performance.  It has been that way for nearly a decade, I'd 
say.  You may disregard that as irrelevant to your app XYZ because any single 
core today is good enough for it, but just look at the introduction of the 
iPhone as an example of how single-threaded performance can drop very abruptly, 
and how you eventually got more cores but not much of a core boost.

And aside from performance, there are many other factors such as latency, 
responsiveness etc that are intertwined with concurrency (in the sense that 
dispatch queues, background threads, etc target all the issues simultaneously) 
which make it wise to get away from a serial world view, even if you don't 
otherwise pro-actively introduce concurrency.

I am almost certainly on the edge of the bell curve, having spent many years 
now working on performance tools and HPC, but I've noticed the curve is 
catching up to me.  To those riding the wave, I can promise you this:  parallel 
programming really isn't that hard.
___

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: [Q] Why is the threading and UI updating designed to be done only on a main thread?

2012-03-15 Thread Wade Tregaskis
> While all these points are very good, I disagree with the conclusion
> because I believe in the wisdom: Keep simple things simple.

An argument for doing this in the frameworks is that it is then simpler to do 
this.  No need for every developer to write the same boiler plate every time.  
And if it's in the frameworks, it'll force people to use it that wouldn't 
bother otherwise, which I'm arguing would be a fundamentally good thing.  In 
the same way to forcing people to follow e.g. MVC entails lots of kicking and 
screaming initially, but is ultimately worth it.

Highly subjective, though, I recognise that.  I think we've pretty much run 
this discussion to its end now, and it doesn't appear I've swayed you.  That's 
okay.

> The one thing I do not understand is, how come you can't just
> implement the threading model that you find most productive for the
> task, on top of the core that receives events in the main thread? This
> can't be hard in most cases, and seems to fit better with the MVC
> approach in most cases: It is the views that receive events, and they
> do truly receive them sequentially. It is your models that may need to
> do things concurrently, not your views. If you need to draw from
> multiple threads, this can be done with the framework as it is.

Well, to be fair, there are a lot of people who think doing any real 
concurrency is hard, and as I noted they're the ones who would benefit most 
from the frameworks providing the infrastructure for them.

There's also no real guarantee that your model is any more or less 
parallelisable than your views, or your controllers.  Event handling might be 
sequential (per document most likely, as I noted) but drawing is usually 
independent per view (sometimes parallelisable within a single view).  And 
maybe that all sits atop a SQLite database that's single-threaded.  Or not.  My 
point is that it's really about a fundamental mindset; serial by default, or 
concurrent by default.  You'll always have to bridge between the two in 
project-specific places.

> But if the whole framework is modelled around an outdated concept, you have a 
> bigger problem than if it's just each application that is.


Of course.  But we shouldn't be too hesitant to make forward progress for fear 
of some unknown opportunity cost.
___

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: How to get Mac codesign certificate?

2012-03-17 Thread Wade Tregaskis
>> But I want to codesign my OS X apps.
>> So how do I get the necessary certificate?
> 
> You need to buy it from a certificate authority, like Thawte or Verisign (or 
> one of the myriad resellers) and they will all be happy to sell you one at 
> prices that range from around $80 to around $500/yr.

Can you not just use a free provider, like http://www.startssl.com/?
___

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: How to get Mac codesign certificate?

2012-03-17 Thread Wade Tregaskis
On 17/03/2012, at 7:54 AM, Marco Tabini wrote:
>> Can you not just use a free provider, like http://www.startssl.com/?
> 
> I'm not an expert, but I think the free cert they provide cannot be used for 
> code signing.

FWIW they can; they'd be pretty useless otherwise.  Many of them are marked, 
however, for use specifically with S/MIME or similar things.  So it really 
boils down to whether there's a special usage that must be marked (nothing in 
the docs about it, if there is), or whether the presence of an extended usage 
field with irrelevant usages defeats it.

It'd be trivial to try it, but it's early in the morning and I'm lazy. :P
___

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: NSData, CFData maximum length question

2012-03-21 Thread Wade Tregaskis
> I'm not sure what [NSMutableData dataWithCapacity:0] does, but it's not a 
> simple call to CFDataCreateMutable(kCFAllocatorDefault, 0) which is why it 
> behaves differently as well.

It probably ignores the specified capacity, for a start.  NSMutableDictionary 
does for its equivalent method, as does NSMutableArray IIRC.
___

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: How to tell which thread is which in the debugger?

2012-03-22 Thread Wade Tregaskis
> I was hoping that the ‘name’ property of the NSThread would show up in the 
> debugger, since it does display names with some threads. But it doesn’t. (Why 
> not?) How can I set a name that will show up in the debugger — do I need to 
> use the pthreads API for that?

You should try pthread_setname_np().  When that was first added (Snow Leopard?) 
it was orthogonal to NSThread's naming scheme (which was basically solely for 
use in the debugger via `po`).  I thought the two had been reconciled - I filed 
the bug suggesting as such, back in the day - but perhaps it didn't happen.
___

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: Can't delete file on device

2012-03-27 Thread Wade Tregaskis
> Okay, I made that change, but it seems blatantly incorrect to create an error 
> return if it is also going to return true.

It only returns you something if it says it did, by indicating that an error 
occurred.  Otherwise, the contents of the error parameter are undefined.

There are definitely some Apple frameworks which will modify the error 
parameter even if they succeed.  There are definitely some which won't.  So you 
can neither rely on it being nil nor on being non-nil, regardless of what you 
initialise it to.

So like it or not, this isn't about preference, it's about correctness.

ARC doesn't change much.  The callee is still free to write something into the 
error parameter and leave it there; it'll merely be released by the caller, 
rather than the callee (which without ARC momentarily leaves a dangling 
pointer).  So it'll reduce the incidence of leaks, but that's about it.
___

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: Is there a list solely for ObjC/compiler language issues?

2012-03-27 Thread Wade Tregaskis
> Just curious... :)

ObjC: objc-langu...@lists.apple.com 
(https://lists.apple.com/mailman/listinfo/objc-language)
Clang: cfe-...@cs.uiuc.edu (http://lists.cs.uiuc.edu/mailman/listinfo/cfe-dev)
___

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: WWDC

2012-04-25 Thread Wade Tregaskis
> I'd probably like to file one asking them to do *several* WWDCs around the 
> world – the cost to people in the bay area is already pretty high ($1.6k ish 
> per attendee), but to someone in the UK, the cost is more like $4k per 
> attendee.  Plus of course doing several would kill the second stone of having 
> more spaces available!

As Scott noted, this isn't as efficient, or really practical in any sense.  As 
it is WWDC has a huge impact on Apple's engineers - aside from the week itself 
(during which only a thousand or so are at WWDC, at most, on any given day) 
there's a lot of preparation for the month or two prior.  Developer relations 
in particular are working their nuts off to not only get the conference itself 
in order, but ancillary things like make sure all the presenters are up to 
snuff, that relevant sample code is ready and to a proper standard, etc etc.

Also, physical presence really isn't that useful.  There is certainly a 
camaraderie that comes from being physically together, which is all warm and 
fuzzy and all, but for the most part boring old telepresence solutions (even 
email, of all things!) is a perfectly good way to work together with an Apple 
engineer.  So what you really should be asking pointed questions about, of 
Apple, is why you can't get in direct contact with relevant engineers 
occasionally.  ("Technical Support Incidents" are (were?) vaguely of this 
nature, though the indirection through developer relations can be problematic 
for everyone involved)
___

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: WWDC

2012-04-25 Thread Wade Tregaskis
> I filed a bug report under "other" asking them to increase the numbers of
> attendees at future WWDC.

I thought this for a long time, but then came to the realisation that what's 
really valuable about WWDC just doesn't scale:  access to Apple engineers.

This wasn't always the case.  The WWDC presentations used to be jealously 
guarded treasures. Now they're much more readily available.  There's still some 
benefit to actually attending - you'll be able to access sessions from the 
conference indefinitely, rather than only for a year or two afterwards - and 
there are networking aspects and 3rd party events etc.  But I think these pale 
in comparison to the exclusive utility of Apple engineer access.

I'd even go so far as to say that today, if you're not spending most of your 
time in the labs or otherwise hunting down people to address specific issues, 
you're detracting from the common good (in the sense that there's a lot of 
others out there who missed out on WWDC tickets who would be doing just that, 
in your place).

Likewise for people that walk into the labs and say things like "So I just 
opened Xcode for the first time - how's it work?".  As an Apple engineer 
working the labs a couple of years, I have to admit I really dreaded that level 
of question, on so many levels.  I couldn't fathom how someone could throw down 
thousands of dollars to attend a conference yet not be enough into development 
to actually use and know a bit about the tools involved.  Treating the 
developer labs like CS 101 is the most expensive class you'll ever pay for.

Keep in mind that if you sufficiently impress an Apple engineer, whether by 
being generally clever / entertaining / generous / interesting - all largely 
functions of the type of problem you go to them with - then some will be 
willing to give you their direct contact details, and you can follow up with 
them after the conference.  Maybe even on other issues, and some time later.  
And they can use that time to really dig into your issue, back in their office, 
and give you a precise answer you just can't get in a face-to-face meeting.
___

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: Minimal document-based app

2012-05-01 Thread Wade Tregaskis
> Unlike other graphical UI layout tools, Interface Builder is central to Cocoa 
> development, not simply a shortcut for newbies or a way to get started 
> quickly. Anyone who thinks developing without Interface Builder is a purer 
> path to understanding Cocoa has already missed the point.

Actually, there are a lot of commercial developers who hard-code their entire 
UIs.  I'm at something of a loss to see why myself, but they do it, and they 
swear it's the best way.  Ironically, one of the reasons often given is "easier 
internationalisation" vs xibs.

Though this does happen more often with iOS than Mac OS, from what I've seen.  
There may be some paradigms refusing to shift with ex- or co-Android 
developers.  Nonetheless it's demonstrably possible.
___

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: Concealing an app from DTrace

2012-05-01 Thread Wade Tregaskis
> Is that the only way? Or is there something easier that would bypass the flag?

There are several that I know of.  But my question first, to you, is why?  I 
can tell you now that you can't reliably defend against all approaches.  What 
you can do is make things really awkward for yourself for debugging, slightly 
awkward for profiling, and problematic for your users as they fail to get 
normal system behaviours like crash reporting.
___

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: Instruments, how to fix leak in C Lib

2012-05-02 Thread Wade Tregaskis
> Bytes Used# LeaksSymbol Name
>  84.81 KB 100.0%48PQgetResult
>  84.81 KB 100.0%48 pqParseInput3
>  80.00 KB  94.3%40  pqResultAlloc
>  80.00 KB  94.3%40   malloc
>   4.00 KB   4.7%4  pqAddTuple
>   4.00 KB   4.7%4   malloc
>832 Bytes0.9%4  PQmakeEmptyPGresult
>832 Bytes0.9%4   malloc
> 
> I thought that inside PQgetResult there ought to be a call to pqParseInput3, 
> inside of which I would then e.g. find a call to pqResultAlloc. But this is 
> not the case. So I thought maybe the compiled version of the C-library I am 
> using here does not match the sourcecode I obtained. I recompiled the library 
> from source, built the Objective-C framework and rebuilt my app and did a new 
> trace, but the leaks' trees were identical also now that I excluded the 
> source for error of there being a difference in version.

Symbolication picks the first known symbol before the address in question.  
It's the consequence of a tragic design flaw in debug info formats to date.

It's more obvious when this goes wrong in Crash Reporter or Shark where you can 
see the offsets (e.g. "CGContextLock + 38623824").

It happens as a result of stripping of debug info from the built library.  This 
is normal practice for release distributions.  That you see it when you build 
from source yourself implies that you either didn't actually get your new 
version of the library loaded as expected, you didn't build it with full debug 
info to begin with, or that at some point some of the info was stripped again.
___

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: architectures that prevent freezing

2012-05-11 Thread Wade Tregaskis
>> While playing with GPU programming, I had a lot of such freeze, and they 
>> never locked the CPU. I was always able to connect to my machine though SSH.

Sometimes you can, sometimes you can't.  It depends on exactly how things fail.

> So a regular user process can permanently lock up the display, requiring a 
> reboot, just by executing some bad GPU code?! That’s kind of a bad privilege 
> violation and could be considered a DoS exploit.

Yes, it is.  A particularly serious one.  It's been a pet peeve of mine for 
years that this is knowingly ignored by those who should know better.

Last I checked, there was a watchdog mechanism on the GPU that would fire after 
some time (7 seconds on nVidia GPUs).  That signals the driver (on the CPU) 
that it's doing a watchdog reset.  Unfortunately, the drivers don't really 
handle that.  They could - and *should* - reinitialise and recover, but it's 
just not implemented (or at least wasn't, a year or two ago).

[[ There's probably also timeouts implemented in the driver and various other 
layers, though I don't know the details. ]]

If you've ever done any CUDA work you'll be all too familiar with this problem. 
 Much of nVidia's own example code will trigger this failure mode, and most 
require a reboot to recover from.

In general GPUs are in a comparative stone-age when it comes to security and 
stability.  They're getting better - retracing the steps of CPUs thirty years 
ago while thinking they're being very clever, in a cutely naive way - but it'll 
probably be many years before these problems are properly resolved.

AMD & Intel are significantly ahead of nVidia in this regard, I hear.  But 
personally, after having every single nVidia-packing machine I've ever owned 
die (sometimes repeatedly) due to GPU-related hardware faults, I'd never buy an 
nVidia based machine to begin with.  But I digress...  back to trying to 
recover data from my 8800GS iMac...  again...
___

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 capacity

2012-05-23 Thread Wade Tregaskis
> Can you not track the capacity yourself? Unless I'm missing something, if you 
> use
> 
>+dataWithCapacity:some_capacity

The docs note that this doesn't necessarily pre-allocate the given capacity.  
You can test that trivially by asking for a capacity of several gigabytes.

In a nutshell, there's no way to "lock" the underlying bytes of NSMutableData 
(or NSMutableString, or anything else like them).  If you mutate them via 
method calls, you need to reset any interior pointers you may have.  Strictly 
speaking you should reset your interior pointers every time you invoke any 
method on them, since they're technically free to re-arrange their internals 
however they like, even for what are [externally] non-mutating methods.

If there's a performance concern, using IMP caching.  The cost of the function 
call to retrieve the bytes pointer is really trivial.
___

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: Calling autorelease on CFAllocated objects?

2008-07-09 Thread Wade Tregaskis
I have a memory management question. I was looking at the QCTV  
example on from the quicktime site. It has some code that does the  
following:


ICMCompressionSessionOptionsRef options;

..

Do some work
..

return (ICMCompressionSessionOptionsRef)[(id)options autorelease];

Can you do this with CoreFoundation allocated things that are not  
bridged?


Autorelease pools ultimately just invoke -(void)release on the  
objects.  If the object is not a true ObjC object or a bridged CF  
object, this will not work.  I'm not sure what the result will be -  
whether it'll crash or do nothing or what.  Fair to say the result is  
undefined and invariably bad.


Wade
___

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 [EMAIL PROTECTED]


Re: Calling autorelease on CFAllocated objects?

2008-07-09 Thread Wade Tregaskis

http://www.cocoabuilder.com/archive/message/cocoa/2008/7/5/212046

I wish this were better documented; the Search Kit docs show  
autorelease being sent to an SKDocumentRef, also, and that's always  
made me nervous (I think I actually sent feedback on that one a long  
time ago).


I do apologise, you are absolutely correct.  The confusion arises from  
the fact that the term "toll-free bridging" is used to describe CF  
objects that have real NS equivalents, functionally.  In fact, all CF  
objects are bridged, in a functional sense - just that by default  
they're bridged to essentially NSObject so all you get is the basic  
NSObject functionality.


So my previous answer was actually right, just not helpful. :D

The documentation could be clearer, yes.  I just filed a bug report  
myself, which I know isn't the first, but if you do encounter places  
in the documentation which talk about toll-free bridging and are  
ambiguous or seemingly contrary to this, please file bug reports for  
those specifically.


Wade
___

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 [EMAIL PROTECTED]


Re: Using performSelector: on super

2008-08-06 Thread Wade Tregaskis
The try/catch setup is well optimized and introduces very little  
overhead. So in the nominal case, where there is no exception,  
there's almost no overhead at all. Even if an exception was  
thrown, NSException is fairly lightweight.


This is not particularly accurate.


There, I'll beg to differ.

Exception handlers are cheap ("zero-cost") to set up in C++ and in  
the

64-bit Objective-C runtime.  They are unfortunately kind of expensive
to set up in 32-bit Objective-C.  They are based on setjmp/longjmp.


setjmp/longjmp is very fast. Or at least it used to. I understand  
that setjmp has slowed down over the years as more and more state  
information needs to be saved to make it work. During my career I've  
implemented setjmp/longjmp a few times and it used to take only  
about a dozen machine instructions to squirrel away the current  
stack pointers into a local structure, return, and perform a  
conditional test. Probably faster than objc_msgSend.


I haven't measured it in ages, but I suspect that it's still  
reasonably fast. I have several performance intensive applications  
that I profile regularly, and my code uses exceptions and try/catch  
blocks a lot. I've never seen setjmp or longjmp show up in Shark as  
a hot spot. So from casual observation, I'd say that try/catch  
blocks don't slow things down too much.


Let me say straight up that I hate exceptions, and code that uses  
them.  So, I am biased, though I've tried not to be with my  
experimentation.


A quick and dirty test program - one which simply throws exceptions as  
fast as possible in a fixed-iteration-count loop, measured using the  
'time' utility - shows me that the whole exception shebang is about  
three or four times more expensive in 64-bit than 32, and that it's at  
least three orders of magnitude slower than returning an int.  (all on  
Intel)  I use that as a somewhat relevant counter-example given the  
traditional argument between error codes and exceptions as prevailing  
models, and given that the original case was using  
instancesRespondToSelector:, which while notably more complex  
ultimately boils down to returning a scalar, rather than creating an  
entire object as with exceptions.  [[ admittedly I'm not considering  
additional messaging overhead ]]


And I quickly discovered the gotcha that since NSExceptions are  
autoreleased, if you happen to be triggering lots of them in a loop  
without explicit pool flushes, you'll unnecessarily enlarge your  
memory footprint.


I'm not presenting numbers since these tests are so primitive, and I  
don't want to go into unnecessary details; the point is well enough  
made.  If anyone wants to do a full analysis with appropriate controls  
and timing and some Shark profiles, be my guest, by all means.


The prevailing wisdom has always been that exceptions are for  
exceptional cases.  Maybe they would more appropriately titled as  
unexpecteds.  Intentionally using them as the foundation for  
determining whether some class supports some optional or unofficial  
interface, or anything of that nature, is a gross abuse of them.  And  
while, granted, you can happily throw thousands, perhaps tens of  
thousands of exceptions a second without a meaningful performance  
impact for most programs, it seems simply a bad and unnecessary habit  
to get into.


The comment that actually riled me enough to jump in on this thread  
was the ever-popular "premature optimisation" card being played.  This  
card is almost always misplayed in discussions like this.  Premature  
optimisation is making a design or implementation choice, on the basis  
of performance, without sufficient facts.  It does not apply  
universally as a wildcard whenever you wish to override someone else's  
approach - arbitrary or not - with your own.  In this case, it is well  
demonstrated and well documented that exceptions are expensive.   
Relying on them for normal control flow is a bad idea, and against  
common wisdom.


It does not need to be proven that it will definitely impact the final  
performance; there is a choice in this case between two functional  
equivalents for which once is clearly more appropriate and less likely  
to become an actual performance issue.  This is not premature  
optimisation, it is simply mindful design.


Wade
___

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 [EMAIL PROTECTED]


Re: what is radar:// supposed to open?

2008-08-16 Thread Wade Tregaskis
sorry not totally cocoa but this is the 2nd or 3rd time I've seen 'radar://' 
, clicked it, and I get an instant crash of something called  
mobilesafari. What's supposed to open radar:// links? I tried safari  
but it just does the same thing.


I'd actually like to be able to track some of these (and other) bugs.


Apple's bug tracking system is for the most part not open to anyone  
outside the company.  The portion that is, the public interface to it,  
is found at http://bugreport.apple.com/, where you can file new bug  
reports and monitor those you've filed to date.  There are no  
provisions for you to be able to look at anyone else's bug reports -  
other than asking them yourself - though you are welcome to contact  
Developer Technical Support (DTS, [EMAIL PROTECTED]) to ask for feedback.   
Typically though they'll still only provide information about the bugs  
you've filed yourself.  I can't and am not speaking on official policy  
as to why this is as it is, though you can probably appreciate the  
privacy and legal issues involved.


As to the URL syntax itself... in a nutshell, it's for the convenience  
of Apple employees for whom clicking on such links does take them  
directly to the report in question.


Wade
___

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 [EMAIL PROTECTED]


Re: Deep Recursion

2008-08-27 Thread Wade Tregaskis
Is there some way (environment variable?) to limit the stack size to  
something smaller, so that the exception (probably from stack  
corruption) would show off earlier?


http://developer.apple.com/qa/qa2005/qa1419.html - Customizing Process  
Stack Size


You can set limits/ulimits, define it at link time (-stack_size), or  
modify it at runtime (setrlimit, pthread_attr_setstacksize, or - on  
Leopard only - -[NSThread setStackSize:]).


Wade
___

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 [EMAIL PROTECTED]


Re: Convert unicode string into ascii

2008-08-28 Thread Wade Tregaskis

is a way to convert an unicode string into a simple a-z>0-9 string
and replace the other wierd chars into a "." (full stop)?

im doing a small hex reader, so maybe this could help you.


CFDataRef CFStringCreateExternalRepresentation (
   CFAllocatorRef alloc,
   CFStringRef theString,
   CFStringEncoding encoding,
   UInt8 lossByte
);
-- OR --
CFIndex CFStringGetBytes (
   CFStringRef theString,
   CFRange range,
   CFStringEncoding encoding,
   UInt8 lossByte,
   Boolean isExternalRepresentation,
   UInt8 *buffer,
   CFIndex maxBufLen,
   CFIndex *usedBufLen
);

Pass kCFStringEncodingASCII as the desired encoding, '.' as your loss  
byte.  That won't limit you to purely alphanumerics - it allows  
spaces, punctuation, etc.  But it may be exactly what you want - it's  
not clear from your original post.


Depending on how you then need to use the result, you may prefer one  
or the other.  In either case it's easy enough to convert back to a  
CFString if that's what you ultimately need.


Wade
___

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 [EMAIL PROTECTED]


Re: Tight loop processing

2008-04-10 Thread Wade Tregaskis
Threads are almost always the right way to do what the OP wants.  The  
problem as was presented is that there's some work to do, which  
happens to be dividable into N segments.  There were no bounds placed  
on how long it takes to run any individual segment.  And even if there  
were, they'd probably be wrong - just about anything your code does  
can be delayed unexpectedly in weird and wonderful ways.


No, the correct approach is to do your work on a separate thread.  In  
Leopard you can send messages between threads trivially using  
performSelector:onThread:withObject:waitUntilDone:, which makes it  
very simple to tell your worker thread to stop, or send results &  
status back to the main thread, etc.


It's worth doing this properly if only for the sake of learning how to  
do it.  Concurrency is the way of the future, like it or not, and  
threads are the primary way to get that concurrency.  They're more  
resistant to numerous failure modes (such as unexpected blocking,  
excessively long work periods, and more) and they scale better - you  
can do other stuff, you could run two threads concurrently to do a  
second set of work, etc.  And, naturally, they give you performance  
scaling that is potentially even better than linear.


Sorry if that all sounds a bit pious, but I personally feel it's  
really important that people don't try to use crutches like timers or  
delayed performs, that are only going to be a liability sooner or later.


Wade
___

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 [EMAIL PROTECTED]


Re: Anyone used btlsocket framework?

2008-05-10 Thread Wade Tregaskis
btlsocket  is a new open-source  
Cocoa framework that provides a high-level API for TCP and UDP  
sockets. On first glance it looks quite nice, definitely a step up  
compared to using NSStreams directly (a la the CocoaEcho sample.)  
But it's so new that I can't find anything about it other than the  
actual project page and source code.


Has anyone used this yet? Does it seem solid?


I haven't used it directly, but I did notice when looking at it that  
it seems to rely on you polling it... that's terrible, given you can  
setup a socket as a runloop source very easily and it operates very  
efficiently.  It seems to me that this API requires you to do a lot  
more work. :/


Wade
___

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 [EMAIL PROTECTED]


Re: Xcode eats 100% CPU and more while typing

2008-05-13 Thread Wade Tregaskis
In any case, I'll definitely be filing a radar next time it  
happens.  Problem is, it's next to impossible get a repro the  
problem given the number of variables (environment, SCM, project,  
the file itself, and whatever UI actions/history that led up to that  
point), so we come back to the strange fact that only certain  
projects seem to be affected.


In hard to reproduce cases like this, often the easiest way to get a  
handle on them is to have Shark sit in the background running a 'Time  
Profile (WTF)' against Xcode while you work, and that'll enable you to  
grab a session including not just the time in which Xcode is  
misbehaving, but also the period leading up to that - often critical  
in figuring out how and even what state the app has gotten itself into.


The overhead of doing this is negligible, and certainly won't impact  
your normal Xcode work.


For more information you can read up on Time Profiling in the Shark  
user manual, and specifically Windowed Time Facility (WTF).


A bug report with such a session attached is much more likely to  
receive attention than simply stating there's a problem.  As noted,  
it's also likely to be more useful than a simple profile or  
traditional 'sample', and is easier to obtain.


Wade
___

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 [EMAIL PROTECTED]


Re: Xcode eats 100% CPU and more while typing

2008-05-13 Thread Wade Tregaskis
For more information you can read up on Time Profiling in the Shark  
user manual, and specifically Windowed Time Facility (WTF).


Somewhere along the way someone ate my links.  Thanks a lot, anonymous  
gremlin. :)


Time Profiling: http://developer.apple.com/documentation/DeveloperTools/Conceptual/SharkUserGuide/TimeProfiling/chapter_3_section_1.html#/ 
/apple_ref/doc/uid/TP40005233-CH3-SW1
Windowed Time Facility (WTF): http://developer.apple.com/documentation/DeveloperTools/Conceptual/SharkUserGuide/SelectingExecutiontoSampleorTrace/chapter_6_section_5.html#/ 
/apple_ref/doc/uid/TP40005233-CH13-SW1


Wade
___

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 [EMAIL PROTECTED]


Re: Performance problem with GC enabled

2009-03-14 Thread Wade Tregaskis

Ah, right, sorry.  I'm not saying the existing API would permit such a
change, more's the pity.  All I'm saying (and I doubt that saying  
this has
any value) is that it could, and in my opinion should, have been  
done that

way in the first place.


It's very tempting to try to enforce this in a CF-based API.  It also  
turns out to be really annoying to use the subsequent API.  If you  
look at CoreFoundation itself, you'll find a lot of void returns  
(what, errors?  impossible!) and non-retaining getters... these make  
it really simple to use and impossible to use safely, and impossible  
to improve the implementation there-of.  You really appreciate this  
the first time you re-implement a function conscious of the fact that  
it now deliberately leaks every time it's called (don't ask, the  
memory still makes me cry).


Having written libraries/frameworks at both the C, CF and Cocoa  
levels, if you told me you were writing one in anything less than  
Objective-C, I would slap you in the face, shake you by the shoulders  
and scream "Why?  Oh god why?".  And you'd better have a damn good  
reason (there are some, but they're thankfully rarely applied), else  
I'll revoke your programming privileges for eighteen months. :P


And though personally I dislike GC, if you said you weren't supporting  
it, I'd be upset much the same.  It should be pretty obvious to  
everyone that GC is ultimately the way forward, and that it's only  
going to get better as time goes on. Reference-counting is virtually  
static.  It will not magically improve in any significant way.  If you  
think GC can never outperform it, even in theory, I'd politely suggest  
you haven't considered the matter very well.


So while it's not a panacea today, complaining about it on lists is  
not productive (as opposed to seeking workarounds in a constructive  
manner, which is entirely appropriate).  Please file bugs, as Bill has  
reiterated over and over.  How many software companies do you  
personally get begged by to optimise your specific use?


Wade
___

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: Accuracy of timers?

2009-04-22 Thread Wade Tregaskis
As others have noted, NSTimers are bound by the runloops they operate  
in.  Though you can always spawn a dedicated thread, create a run  
loop, add your timer, and then go; since nothing else is in the  
runloop, the latency should be quite low.  I'd try that first, and see  
if it meets your needs.


Failing that, you can move down to a lower level - one approach I've  
seen used successfully in several latency-sensitive apps is  
pthread_cond_timedwait (on a condition that never necessarily gets  
signalled, though that can be a convenient way to cancel your timer).   
Kind of obtuse, but it's highly portable and I don't know of a  
canonical "wait" function of comparable precision.  It's still a "wait  
for duration" rather than "wait for time" though; I don't know off  
hand of any way to [reliably] do the latter.


setitimer was suggested, but personally I try to avoid signals  
wherever possible, plus:


a) You can only have one (of each of the three types, but nonetheless).
b) It's formally defined as having "tick" resolution, which doesn't  
strictly make sense on Mac OS X but is in any case orders of magnitude  
above microseconds.  I think on Mac OS X it actually provides  
microsecond resolution, but that's not something you can technically  
rely on (especially if you're writing portable code).


If you have a dedicated thread you can also raise its priority or try  
making it real-time, to give yourself a further edge.


Wade

P.S. For completeness I should mention of course nanosleep, but I  
don't know of its precision and in any case it can be interrupted by  
signals, which makes it more difficult to use than you'd expect.

___

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: CF autorelease?

2009-04-23 Thread Wade Tregaskis
Something I've been using as of late to make CF a little more bearable  
is the cleanup attribute offered by gcc, e.g.:



static inline void _autoreleaseCFArray(CFArrayRef *array) {
if (NULL != *array) {
CFRelease(*array);
}
}

#define CFAutoreleasedArrayRef  
__attribute__((cleanup(_autoreleaseCFArray))) CFArrayRef


Unfortunately there's an apparent bug in gcc that requires you to have  
exact type matches, so you can't make e.g. a generic CFTypeRef variant  
(unless your variables really are declared as CFTypeRefs).  But still,  
if you're using a particular set of objects a lot, it can save you so  
much work.


Don't be confused by the terminology, though; this'll only  
"autorelease" whatever's assigned to that variable when it goes out of  
scope.  If you modify the pointer or clear it, you won't get that  
autorelease.  For simple uses this is fine, I find.  If your  
background is predominately C++ you might be more comfortable with an  
"Auto" naming scheme instead.


Wade
___

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: CF autorelease?

2009-04-23 Thread Wade Tregaskis
Another caveat with cleanup is that it is not guaranteed to be  
called.  For this audience, the most likely way this will bite you  
is when the new zero cost objective-c exceptions aren't available  
(i386, ppc) and an exception is thrown.  If zero cost objective-c  
exceptions are available, then the compiler arranges to have the  
cleanup function called during the stack unwind.


There's enough gotchas to cleanup that I definitely wouldn't count  
on it for proper memory management.


Admittedly I wasn't aware of that (it's also not called if you invoke  
exit or abort, but that's kind of expected).  However, exceptions are  
not usually safe to use through vanilla C code anyway, whether CF- 
based or otherwise, so that's a moot point (if you were using C++, you  
could use the template Peter Lewis suggested, and if you're using ObjC  
you can just autorelease directly).  Good that you pointed it out  
though.


Wade
___

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: Charting API? (Chris Schmitt)

2008-02-27 Thread Wade Tregaskis
Apple has the makings of such a framework already - its called  
GraphKit.


If you want GraphKit to become available as a supported Cocoa  
framework PLEASE enter an enhancement bug - you can reference the  
same bug my request was dupped to: 3320659 [its low number tells you  
its a long standing request!].


Even if you don't care - enter a bug anyway, and help the rest of  
us! 1,000 more bugs on this issue and we'll surely see GraphKit in  
the next big-cat release!


Rather than asking for a specific SPI to be made public, you'll likely  
do better for yourself if you file a general feature request,  
explaining what you need in terms of graphing, what sort of features  
you're interested in, the volume of and how you manage your data, and  
so forth... there are many, many ways to implement a graphing API, and  
there's no point in Apple providing one without knowing what most  
developers actually expect from it.  For example, there's a very big  
difference between what say Keynote needs, in terms of graphing, and  
what a scientific visualisation program needs.


Wade
___

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 [EMAIL PROTECTED]